mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-01 18:03:41 +08:00
Remove migrated companion apps and refresh docs, update credits for app developers, and production app store links
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
name: Galaxy phone bridge
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [Dom, StarPilot, secretgood-ios-integration]
|
||||
paths:
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/galaxy-phone-bridge.yaml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/galaxy-phone-bridge.yaml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: galaxy-phone-bridge-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
bridge:
|
||||
name: Comma Bluetooth bridge tests
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: false
|
||||
lfs: false
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install bridge test dependencies
|
||||
run: python -m pip install pycryptodome
|
||||
- name: Run bridge regressions
|
||||
run: python -m unittest discover -s openpilot/starpilot/galaxy_bluetooth/tests -v
|
||||
@@ -1,69 +0,0 @@
|
||||
name: iOS companion
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [Dom, StarPilot, secretgood-ios-integration]
|
||||
paths:
|
||||
- 'openpilot/starpilot/companion/ios/**'
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/ios-companion.yaml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'openpilot/starpilot/companion/ios/**'
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/ios-companion.yaml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ios-companion-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
app:
|
||||
name: Swift tests and iOS Simulator build
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 25
|
||||
defaults:
|
||||
run:
|
||||
working-directory: openpilot/starpilot/companion/ios
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: false
|
||||
lfs: false
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Run companion regressions
|
||||
env:
|
||||
CI_PRIMARY_REPOSITORY_PATH: ${{ github.workspace }}/openpilot/starpilot/companion/ios
|
||||
run: sh ci_scripts/ci_post_clone.sh
|
||||
- name: Build for iOS Simulator
|
||||
run: >-
|
||||
xcodebuild -project GalaxyBluetooth.xcodeproj
|
||||
-scheme GalaxyBluetooth -configuration Debug
|
||||
-sdk iphonesimulator -destination 'generic/platform=iOS Simulator'
|
||||
-derivedDataPath "$RUNNER_TEMP/galaxy-ios-build"
|
||||
CODE_SIGNING_ALLOWED=NO build
|
||||
|
||||
bridge:
|
||||
name: Comma Bluetooth bridge tests
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: false
|
||||
lfs: false
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Install bridge test dependencies
|
||||
run: python -m pip install pycryptodome
|
||||
- name: Run bridge regressions
|
||||
run: python -m unittest discover -s openpilot/starpilot/galaxy_bluetooth/tests -v
|
||||
@@ -1,5 +1,9 @@
|
||||
# Source provenance
|
||||
|
||||
## Phone companions and Galaxy contributions
|
||||
|
||||
[dirwin31](https://github.com/dirwin31/StarPilotAndroid) developed the Android companion and contributed StarPort setup, wireless adapter compatibility, connectivity fixes and diagnostics ([PR #273](https://github.com/StarPilotHQ/StarPilot/pull/273)). [natehuby76](https://github.com/natehuby76/StarPilotBT) developed the iOS companion and contributed Galaxy Bluetooth pairing, local Wi-Fi discovery and UI fixes, including the C4 menu reset ([PR #246](https://github.com/StarPilotHQ/StarPilot/pull/246)). Their work helped make phone integration and everyday use more reliable. The apps are maintained separately under their respective licenses.
|
||||
|
||||
## Jetlink external inference
|
||||
|
||||
The comma-side Jetlink client and USB transport in `jetlink_repo` are by Zeph Leggett and the [Jetlink contributors](https://github.com/zoompilot/jetlink). They are vendored from revision `9cfde98eec1d7cc714d800504944cf1a3944513d` under the MIT license, retained in [jetlink_repo/LICENSE](jetlink_repo/LICENSE). StarPilot's adapter (`openpilot/starpilot/models/jetlink_adapter.py`) builds on Jetlink's openpilot layer and owns its param names, Always On Lateral rule, model runner reset, settings and alerts. Companion applications and inference servers remain distributed by Jetlink.
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
[](https://firestar.link/discord)
|
||||
[](https://github.com/StarPilotHQ/StarPilot)
|
||||
[](https://wiki.firestar.link)
|
||||
[](https://apps.apple.com/ca/app/starpilot-bt/id6821039119)
|
||||
[](https://groups.google.com/g/galaxy-starpilot-android-beta)
|
||||
[](https://apps.apple.com/ca/app/starpilot-bt/id6821039119)
|
||||
[](https://play.google.com/store/apps/details?id=com.starpilot.galaxy)
|
||||
|
||||
**StarPilot** is a custom fork of [comma.ai's openpilot](https://comma.ai/openpilot),
|
||||
an open source driver assistance system.
|
||||
@@ -55,7 +55,11 @@ installation guides, and software configuration.
|
||||
Auto tuning system to adapt openpilot to *your* car's unique lateral characteristics.
|
||||
* Galaxy: StarPilot's portal to configure your comma device using your phone from anywhere.
|
||||
Download models, change settings, update software, diagnostics, manage dashcam video, and more.
|
||||
* Navigation - Display routes and give the driving model hints on taking exits and turns.
|
||||
* Android and iOS companion apps - Access Galaxy over Wi-Fi, Firestar Link (HTTPS), or Bluetooth.
|
||||
* StarPort - Project StarPilot onto compatible Android Auto head units for a larger driving display.
|
||||
* Customizable driving display - Driving map and navigation widgets, plus music controls and Jetlink status in StarPort.
|
||||
* Spotify Connect and phone audio - Play through compatible car speakers over StarPort or Bluetooth.
|
||||
* Navigation - Mapbox or Google maps and routing, with route guidance for exits and turns.
|
||||
* Always On Lateral (full time steering assist)
|
||||
* Lane Centering - Enable to center between detected lane lines,
|
||||
with graceful fallback to model E2E lateral outputs and safety breakout
|
||||
|
||||
@@ -118,21 +118,20 @@ SOFTWARE.
|
||||
|
||||
`openpilot/starpilot/soloist/pulseaudio/` contains unmodified AArch64 binaries from Ubuntu 24.04 packages: PulseAudio 16.1 (LGPL-2.1-or-later), libltdl (LGPL-2.1-or-later), libtdb (LGPL-3.0-or-later), libsoxr (LGPL-2.1-or-later), liborc and speexdsp (BSD-style). The complete copyright and license notices are in that directory's `licenses/`, package hashes in `PACKAGES.sha512`, and the corresponding source is available from Ubuntu's archive for the exact versions listed in its README. The libraries are dynamically linked and may be replaced with `update.sh`.
|
||||
|
||||
## Galaxy Android companion tunnel
|
||||
## Comma-side phone internet tunnel
|
||||
|
||||
`openpilot/starpilot/galaxy/bin/hev-socks5-tunnel_linux_arm64` is the upstream
|
||||
[hev-socks5-tunnel 2.18.0](https://github.com/heiher/hev-socks5-tunnel/releases/tag/2.18.0)
|
||||
static Linux ARM64 release, under the MIT license. Its notice is retained in
|
||||
`openpilot/starpilot/galaxy/bin/LICENSE.hev-socks5-tunnel`; the adjacent SHA-256
|
||||
file pins the downloaded artifact. The Android companion uses the Kotlin
|
||||
standard library (Apache-2.0) and the Gradle wrapper (Apache-2.0); no third-party
|
||||
UI framework is bundled.
|
||||
[LICENSE.hev-socks5-tunnel](openpilot/starpilot/galaxy/bin/LICENSE.hev-socks5-tunnel);
|
||||
the adjacent SHA-256 file pins the downloaded artifact.
|
||||
|
||||
## Galaxy Bluetooth companion source snapshot
|
||||
## Comma-side Galaxy Bluetooth bridge
|
||||
|
||||
The Galaxy Bluetooth phone bridge from [StarPilotHQ/StarPilot](https://github.com/StarPilotHQ/StarPilot)
|
||||
(natehuby76, PRs #224/#225) is included under `openpilot/starpilot/galaxy_bluetooth/`,
|
||||
with its license in [UPSTREAM-LICENSE](openpilot/starpilot/galaxy_bluetooth/UPSTREAM-LICENSE).
|
||||
|
||||
The Galaxy Bluetooth phone bridge and iOS app from https://github.com/StarPilotHQ/StarPilot
|
||||
(natehuby76, PRs #224/#225) are included under `openpilot/starpilot/galaxy_bluetooth/`
|
||||
and `openpilot/starpilot/companion/ios/`, with their license files (`UPSTREAM-LICENSE`, `openpilot/starpilot/companion/ios/UPSTREAM-GALAXY-LICENSE`).
|
||||
The bridge runs on openpilot's Python with PyCryptodome 3.23.0 (BSD/public-domain
|
||||
components, from opendbc). Its other dependencies are vendored unmodified, as
|
||||
pure-Python sources, in `openpilot/starpilot/galaxy_bluetooth/vendor/`:
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
# StarPilot companion apps
|
||||
|
||||
Phone apps for Galaxy. Both talk to the comma over Wi-Fi/LAN or Bluetooth and
|
||||
share one pairing key.
|
||||
|
||||
```
|
||||
companion/
|
||||
├── android/ Android app (Gradle project, build_apk.sh, host tests)
|
||||
├── ios/ iPhone app (Xcode project, CarPlay, tests) — see ios/README.md
|
||||
└── run_host_tests.py
|
||||
```
|
||||
|
||||
The comma side lives elsewhere:
|
||||
|
||||
- `openpilot/starpilot/galaxy_bluetooth/` — Bluetooth bridge, LAN discovery and
|
||||
the pairing screen, run by the `galaxy_phone` process.
|
||||
- `openpilot/starpilot/galaxy/companion*.py` — phone internet sharing.
|
||||
|
||||
Over Bluetooth, pairing, phone internet sharing, APK downloads, recordings,
|
||||
replay, cameras and map tiles are blocked; they need Wi-Fi.
|
||||
|
||||
## Pairing and phone music
|
||||
|
||||
One step pairs the app and phone music. On comma open Settings → Bluetooth →
|
||||
**Pair phone**; comma opens a two-minute window that takes one phone.
|
||||
|
||||
Before pairing over Wi-Fi/LAN the app asks comma `GET /api/companion/bluetooth-ready` and waits out a boot or a
|
||||
Bluetooth bridge restart; it stops with the reason (not parked, Bluetooth off or unavailable) instead of scanning.
|
||||
If the app already reaches comma over Wi-Fi/LAN, **Add Bluetooth Phone Pairing** (Android) or **Pair with comma** (iPhone) opens that window itself (the call
|
||||
Galaxy's Bluetooth page makes), so nothing needs touching on comma. Without a Wi-Fi/LAN session it waits for
|
||||
the window as above.
|
||||
|
||||
- Android: tap **Add Bluetooth Phone Pairing** in the app. If the app can't reach comma over Wi-Fi it first asks you to open
|
||||
**Pair phone** on comma and keep it open. It then gets its key, bonds for music and shows one system prompt to approve.
|
||||
The first time Galaxy opens over Wi-Fi/LAN on a phone with no comma key (or an expired one), the app offers
|
||||
**Add pairing**. It opens comma's pairing window itself, shows each step, and asks for the Nearby devices permission if
|
||||
needed. **Not now** asks again next launch; **Don't ask again** leaves it to **Add Bluetooth Phone Pairing** in the menu.
|
||||
- iPhone: tap **Pair with comma** in the app, then tap comma once in
|
||||
Settings → Bluetooth (iOS cannot start a Bluetooth bond from an app).
|
||||
- No app: tap comma in the phone's Bluetooth settings to pair music only.
|
||||
|
||||
Forgetting a Bluetooth device in comma Settings also removes its app key. On Android, forgetting comma in the phone's
|
||||
Bluetooth settings removes the app pairing too, and if comma no longer recognizes the phone's key the app stops retrying
|
||||
and says the pairing expired until you pair again. Installing
|
||||
Spotify (`/api/spotify/upload`) is blocked over Bluetooth like the other large uploads.
|
||||
|
||||
## Phone GPS
|
||||
|
||||
Each app can send the phone's GPS to comma about once a second, over Bluetooth or
|
||||
Galaxy Wi-Fi. Comma carries it inside the navigation message as `phoneGps`, keeps the last fix for
|
||||
10 seconds, and navigation uses it only when comma's own GPS and the car's GPS have no fix. Galaxy → Navigation → GPS Source can
|
||||
instead ignore the phone or prefer it; mapd follows the same choice.
|
||||
|
||||
The 10-second hold is an expiry allowance, not an update interval. Navigation
|
||||
checks for new phone fixes five times a second and forwards each new measurement
|
||||
at the next check; without new fixes it publishes its usual once-a-second heartbeat.
|
||||
The car map smooths movement between fixes using speed and heading for at most
|
||||
2.5 seconds, then holds the position until another fix arrives or the hold expires.
|
||||
Stationary phones retain the full 10-second allowance without predicted movement.
|
||||
|
||||
- Android: Connections → **Share phone GPS with comma**. Runs as a foreground
|
||||
service with a notification.
|
||||
|
||||
`POST /api/companion/location` with JSON: `latitude`, `longitude`,
|
||||
`horizontalAccuracy` (m) and `ageMs` (phone-measured age, at most 2000) are
|
||||
required; `altitude`, `verticalAccuracy`, `speed`, `speedAccuracy`, `bearing`,
|
||||
`bearingAccuracy` and `timestamp` (Unix ms) are optional. Leave out unknown
|
||||
values. Comma dates the fix by its own clock minus `ageMs`, never by `timestamp`.
|
||||
Refused through the remote tunnel.
|
||||
|
||||
## Android
|
||||
|
||||
Install: join the Galaxy hotspot, open Galaxy → **Galaxy Access & Install** →
|
||||
**Android companion**, and install the APK. Later updates install from inside
|
||||
the app: tap **Update app** while connected over Galaxy Wi-Fi/LAN, allow
|
||||
installation from StarPilot if Android asks, and confirm the Android update dialog.
|
||||
The APK streams into Android's installer; there is no file to find in Downloads.
|
||||
After replacement, an **Update installed → Reopen** notification opens the new app.
|
||||
Enable app notifications for this prompt. If notifications are disabled, open
|
||||
StarPilot normally; the app confirms the completed update on launch.
|
||||
|
||||
### When an APK rebuild is needed
|
||||
|
||||
| Change | Rebuild Android APK? |
|
||||
| --- | --- |
|
||||
| Kotlin/Java code, native bridge, updater, phone GPS, Bluetooth or services | Yes |
|
||||
| Android manifest, permissions, resources, icons, Gradle config or dependencies | Yes |
|
||||
| Files in `android/app/src/main/assets/`, including `bluetooth-fetch.js` | Yes |
|
||||
| Galaxy HTML/CSS/JS used over Bluetooth | No: the app downloads these pages from comma over Wi-Fi/LAN (see below) |
|
||||
| Galaxy HTML/CSS/JS used over Wi-Fi/LAN | No: screens load from comma |
|
||||
| Comma-side Python/services/API changes only | No, unless the phone protocol also needs a change |
|
||||
|
||||
### Galaxy screens over Bluetooth
|
||||
|
||||
Neither app bundles Galaxy's pages. Bluetooth Galaxy shows a copy the app saved from comma, so **connect to comma over
|
||||
Wi-Fi/LAN once** before using Bluetooth. Until then the Bluetooth route says it needs one Wi-Fi visit.
|
||||
|
||||
- Whenever the phone reaches comma over Wi-Fi/LAN (and from **Refresh Galaxy screens** in the menu), the app reads
|
||||
`GET /api/companion/web-manifest`, which lists every file in `galaxy/web` with its SHA-256 and comma's commit. It downloads
|
||||
only the files that changed, verifies each hash, and keeps the old copy if anything fails.
|
||||
- The pages come from comma itself, so custom and unpushed branches work and nothing depends on GitHub.
|
||||
- If comma updated since the last Wi-Fi visit, Bluetooth still opens the saved copy and says it is from an older comma build.
|
||||
Join comma's Wi-Fi to refresh.
|
||||
- A comma without the manifest route is too old to share its screens; update comma.
|
||||
|
||||
### Handing the signing key to another developer
|
||||
|
||||
Updates install over an existing app only when signed with the same `companion.jks`; a different key forces every user to
|
||||
uninstall first. To pass signing on, copy `~/.starpilot/companion.jks` and `~/.starpilot/companion-signing-password` to the
|
||||
new developer over a private channel (a password manager share, not git or chat), or have them point `COMPANION_KEYSTORE`
|
||||
and `COMPANION_PASSWORD_FILE` at wherever the files live. Keep a backup: losing the key means a forced reinstall.
|
||||
|
||||
## Tests
|
||||
|
||||
From the repo root:
|
||||
|
||||
```sh
|
||||
uv run --extra testing --with pycryptodome==3.23.0 --with dbus-next==0.2.3 --with zeroconf==0.151.3 \
|
||||
python openpilot/starpilot/companion/run_host_tests.py
|
||||
node --test openpilot/starpilot/companion/android/tests/test_bluetooth_fetch.mjs
|
||||
(cd openpilot/starpilot/companion/android && ./gradlew testDebugUnitTest)
|
||||
```
|
||||
|
||||
`run_host_tests.py` stubs native modules so it runs on a laptop; it also takes
|
||||
explicit test paths. iPhone tests are in `ios/README.md`.
|
||||
@@ -1,5 +0,0 @@
|
||||
.gradle/
|
||||
.kotlin/
|
||||
**/build/
|
||||
local.properties
|
||||
*.jks
|
||||
@@ -1,342 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
================================================================================
|
||||
Licenses for included components:
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
3-Clause BSD License
|
||||
https://opensource.org/licenses/BSD-3-Clause
|
||||
|
||||
com.esotericsoftware.kryo:kryo
|
||||
com.esotericsoftware.minlog:minlog
|
||||
com.github.mwiede:jsch
|
||||
org.antlr:antlr4-runtime
|
||||
org.eclipse.jgit:org.eclipse.jgit
|
||||
org.eclipse.jgit:org.eclipse.jgit.ssh.apache
|
||||
org.eclipse.jgit:org.eclipse.jgit.ssh.apache.agent
|
||||
org.ow2.asm:asm
|
||||
org.ow2.asm:asm-commons
|
||||
org.ow2.asm:asm-tree
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Apache License, Version 2.0
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
com.amazonaws:aws-java-sdk-core
|
||||
com.amazonaws:aws-java-sdk-kms
|
||||
com.amazonaws:aws-java-sdk-s3
|
||||
com.amazonaws:aws-java-sdk-sts
|
||||
com.amazonaws:jmespath-java
|
||||
com.fasterxml.jackson.core:jackson-annotations
|
||||
com.fasterxml.jackson.core:jackson-core
|
||||
com.fasterxml.jackson.core:jackson-databind
|
||||
com.fasterxml.jackson.datatype:jackson-datatype-jdk8
|
||||
com.fasterxml.jackson.datatype:jackson-datatype-jsr310
|
||||
com.fasterxml.jackson:jackson-bom
|
||||
com.github.jnr:jnr-constants
|
||||
com.google.api-client:google-api-client
|
||||
com.google.apis:google-api-services-storage
|
||||
com.google.code.findbugs:jsr305
|
||||
com.google.code.gson:gson
|
||||
com.google.errorprone:error_prone_annotations
|
||||
com.google.guava:failureaccess
|
||||
com.google.guava:guava
|
||||
com.google.http-client:google-http-client
|
||||
com.google.http-client:google-http-client-apache-v2
|
||||
com.google.http-client:google-http-client-gson
|
||||
com.google.oauth-client:google-oauth-client
|
||||
com.googlecode.jatl:jatl
|
||||
com.thoughtworks.qdox:qdox
|
||||
commons-codec:commons-codec
|
||||
commons-io:commons-io
|
||||
io.grpc:grpc-context
|
||||
io.opencensus:opencensus-api
|
||||
io.opencensus:opencensus-contrib-http-util
|
||||
it.unimi.dsi:fastutil
|
||||
javax.inject:javax.inject
|
||||
joda-time:joda-time
|
||||
net.rubygrapefruit:native-platform
|
||||
net.rubygrapefruit:native-platform-freebsd-amd64-libcpp
|
||||
net.rubygrapefruit:native-platform-linux-aarch64
|
||||
net.rubygrapefruit:native-platform-linux-aarch64-ncurses5
|
||||
net.rubygrapefruit:native-platform-linux-aarch64-ncurses6
|
||||
net.rubygrapefruit:native-platform-linux-amd64
|
||||
net.rubygrapefruit:native-platform-linux-amd64-ncurses5
|
||||
net.rubygrapefruit:native-platform-linux-amd64-ncurses6
|
||||
net.rubygrapefruit:native-platform-osx-aarch64
|
||||
net.rubygrapefruit:native-platform-osx-amd64
|
||||
net.rubygrapefruit:native-platform-windows-aarch64
|
||||
net.rubygrapefruit:native-platform-windows-aarch64-min
|
||||
net.rubygrapefruit:native-platform-windows-amd64
|
||||
net.rubygrapefruit:native-platform-windows-amd64-min
|
||||
net.rubygrapefruit:native-platform-windows-i386
|
||||
net.rubygrapefruit:native-platform-windows-i386-min
|
||||
org.apache.ant:ant
|
||||
org.apache.ant:ant-antlr
|
||||
org.apache.ant:ant-launcher
|
||||
org.apache.commons:commons-compress
|
||||
org.apache.commons:commons-lang3
|
||||
org.apache.groovy:groovy
|
||||
org.apache.groovy:groovy-ant
|
||||
org.apache.groovy:groovy-astbuilder
|
||||
org.apache.groovy:groovy-bom
|
||||
org.apache.groovy:groovy-datetime
|
||||
org.apache.groovy:groovy-dateutil
|
||||
org.apache.groovy:groovy-docgenerator
|
||||
org.apache.groovy:groovy-groovydoc
|
||||
org.apache.groovy:groovy-json
|
||||
org.apache.groovy:groovy-nio
|
||||
org.apache.groovy:groovy-templates
|
||||
org.apache.groovy:groovy-xml
|
||||
org.apache.httpcomponents:httpclient
|
||||
org.apache.httpcomponents:httpcore
|
||||
org.apache.ivy:ivy
|
||||
org.apache.maven:maven-builder-support
|
||||
org.apache.maven:maven-model
|
||||
org.apache.maven:maven-repository-metadata
|
||||
org.apache.maven:maven-settings
|
||||
org.apache.maven:maven-settings-builder
|
||||
org.apache.sshd:sshd-osgi
|
||||
org.apache.sshd:sshd-sftp
|
||||
org.codehaus.plexus:plexus-cipher
|
||||
org.codehaus.plexus:plexus-interpolation
|
||||
org.codehaus.plexus:plexus-sec-dispatcher
|
||||
org.codehaus.plexus:plexus-utils
|
||||
org.fusesource.jansi:jansi
|
||||
org.gradle.fileevents:gradle-fileevents
|
||||
org.jctools:jctools-core
|
||||
org.jetbrains.kotlin:kotlin-assignment-compiler-plugin-embeddable
|
||||
org.jetbrains.kotlin:kotlin-build-tools-impl
|
||||
org.jetbrains.kotlin:kotlin-compiler-embeddable
|
||||
org.jetbrains.kotlin:kotlin-daemon-embeddable
|
||||
org.jetbrains.kotlin:kotlin-reflect
|
||||
org.jetbrains.kotlin:kotlin-sam-with-receiver-compiler-plugin
|
||||
org.jetbrains.kotlin:kotlin-script-runtime
|
||||
org.jetbrains.kotlin:kotlin-scripting-common
|
||||
org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable
|
||||
org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable
|
||||
org.jetbrains.kotlin:kotlin-scripting-jvm
|
||||
org.jetbrains.kotlin:kotlin-scripting-jvm-host
|
||||
org.jetbrains.kotlin:kotlin-stdlib
|
||||
org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm
|
||||
org.jetbrains.kotlinx:kotlinx-serialization-bom
|
||||
org.jetbrains.kotlinx:kotlinx-serialization-core
|
||||
org.jetbrains.kotlinx:kotlinx-serialization-core-jvm
|
||||
org.jetbrains.kotlinx:kotlinx-serialization-json
|
||||
org.jetbrains.kotlinx:kotlinx-serialization-json-jvm
|
||||
org.jetbrains:annotations
|
||||
org.jspecify:jspecify
|
||||
org.objenesis:objenesis
|
||||
org.slf4j:jcl-over-slf4j
|
||||
org.slf4j:log4j-over-slf4j
|
||||
org.tomlj:tomlj
|
||||
org.yaml:snakeyaml
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Bouncy Castle Licence
|
||||
https://www.bouncycastle.org/licence.html
|
||||
|
||||
org.bouncycastle:bcpg-jdk18on
|
||||
org.bouncycastle:bcprov-jdk18on
|
||||
org.bouncycastle:bcutil-jdk18on
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Eclipse Public License 2.0
|
||||
https://www.eclipse.org/legal/epl-v20.html
|
||||
|
||||
org.junit:junit-bom
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
LGPL 2.1
|
||||
https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
|
||||
|
||||
com.github.javaparser:javaparser-core
|
||||
jcifs:jcifs
|
||||
net.java.dev.jna:jna
|
||||
net.java.dev.jna:jna-platform
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
MIT License
|
||||
https://opensource.org/licenses/MIT
|
||||
|
||||
com.googlecode.plist:dd-plist
|
||||
org.jsoup:jsoup
|
||||
org.slf4j:jul-to-slf4j
|
||||
org.slf4j:slf4j-api
|
||||
@@ -1,9 +0,0 @@
|
||||
# Galaxy for Android
|
||||
|
||||
**Galaxy** is the Android companion app for StarPilot. Its Google Play listing name is **Galaxy: StarPilot Companion**.
|
||||
|
||||
The Android app source is provided under the repository's MIT license. See the repository root `LICENSE` for its terms.
|
||||
|
||||
## Privacy policy
|
||||
|
||||
The [privacy policy](docs/privacy-policy.md) describes the app's permissions, local storage, optional location sharing, Bluetooth pairing, and mobile data use. The rendered Markdown page can be used as the policy webpage if the repository is public and the page is accessible without signing in. Use its stable HTTPS URL in the Google Play Console privacy policy field, and make the policy reachable from within the app before publishing.
|
||||
@@ -1,27 +0,0 @@
|
||||
plugins { id("com.android.application") }
|
||||
|
||||
android {
|
||||
namespace = "link.firestar.companion"
|
||||
compileSdk = 37
|
||||
defaultConfig {
|
||||
applicationId = "link.firestar.companion"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 32
|
||||
versionName = "1.1.30"
|
||||
}
|
||||
signingConfigs {
|
||||
create("companion") {
|
||||
storeFile = file(System.getenv("COMPANION_KEYSTORE") ?: "${System.getProperty("user.home")}/.starpilot/companion.jks")
|
||||
storePassword = System.getenv("COMPANION_KEY_PASSWORD")
|
||||
keyAlias = "companion"
|
||||
keyPassword = System.getenv("COMPANION_KEY_PASSWORD")
|
||||
}
|
||||
}
|
||||
buildTypes { getByName("release") { signingConfig = signingConfigs.getByName("companion") } }
|
||||
buildFeatures { buildConfig = true }
|
||||
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
|
||||
}
|
||||
|
||||
dependencies { testImplementation("junit:junit:4.13.2") }
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
<application android:theme="@style/AppTheme" android:label="StarPilot" android:icon="@mipmap/ic_launcher"
|
||||
android:allowBackup="false" android:networkSecurityConfig="@xml/network_security_config">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTask"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".ShareActivity" android:exported="true" android:theme="@style/AppTheme">
|
||||
<intent-filter><action android:name="android.intent.action.SEND" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="text/plain" /></intent-filter>
|
||||
<intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="geo" /><data android:scheme="google.navigation" /></intent-filter>
|
||||
</activity>
|
||||
<receiver android:name=".BootReceiver" android:exported="false"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /></intent-filter></receiver>
|
||||
<receiver android:name=".AppInstallReceiver" android:exported="false" />
|
||||
<receiver android:name=".AppUpdateCompletion" android:exported="false">
|
||||
<intent-filter><action android:name="android.intent.action.MY_PACKAGE_REPLACED" /></intent-filter>
|
||||
</receiver>
|
||||
<service android:name=".UplinkService" android:exported="false" android:foregroundServiceType="connectedDevice" />
|
||||
<service android:name=".PhoneGpsService" android:exported="false" android:foregroundServiceType="location" />
|
||||
<service android:name=".AppUpdateJob" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -1,43 +0,0 @@
|
||||
(() => {
|
||||
const original = window.fetch.bind(window)
|
||||
const pending = new Map()
|
||||
let sequence = 0
|
||||
window.__galaxyBleReply = (id, value) => {
|
||||
const item = pending.get(id)
|
||||
if (!item) return
|
||||
pending.delete(id)
|
||||
item.signal?.removeEventListener('abort', item.abort)
|
||||
if (value.error) { item.reject(new Error(value.error)); return }
|
||||
const data = Uint8Array.from(atob(value.body || ''), c => c.charCodeAt(0))
|
||||
item.resolve(new Response([204, 304].includes(value.status) ? null : data, {status: value.status, headers: value.headers}))
|
||||
}
|
||||
window.fetch = async (input, options = {}) => {
|
||||
const request = new Request(input, options)
|
||||
const url = new URL(request.url, location.href)
|
||||
if (url.origin !== location.origin) throw new Error('External resources are not available over Bluetooth. Connect using Galaxy Wi-Fi or LAN.')
|
||||
if (url.pathname === '/data/runtime.json') url.pathname = '/api/companion/runtime'
|
||||
if (!url.pathname.startsWith('/api/')) return original(input, options)
|
||||
if (['/api/companion/bluetooth', '/api/recordings/', '/api/replay/', '/api/cameras/', '/api/starport/upload', '/api/spotify/upload', '/api/navigation/map/tiles/'].some(path => url.pathname.startsWith(path)) ||
|
||||
['/api/companion/uplink', '/api/companion/app.apk', '/api/auth/login', '/api/auth/logout'].includes(url.pathname)) {
|
||||
return new Response(JSON.stringify({error: 'This action is not available over Bluetooth. Connect using Galaxy Wi-Fi or LAN.', code: 'bluetooth_unavailable'}), {status: 501, headers: {'Content-Type': 'application/json'}})
|
||||
}
|
||||
if (request.signal.aborted) throw new DOMException('Request canceled', 'AbortError')
|
||||
const bytes = new Uint8Array(await request.arrayBuffer())
|
||||
if (bytes.length > 1048576) throw new Error('Large uploads are not available over Bluetooth. Connect using Galaxy Wi-Fi or LAN.')
|
||||
let body = ''
|
||||
for (let i = 0; i < bytes.length; i += 8192) body += String.fromCharCode(...bytes.subarray(i, i + 8192))
|
||||
const id = String(++sequence)
|
||||
return new Promise((resolve, reject) => {
|
||||
const abort = () => {
|
||||
pending.delete(id)
|
||||
StarPilotBLE.cancel(id)
|
||||
reject(new Error(['GET', 'HEAD'].includes(request.method) ? 'Bluetooth request canceled' : 'Connection interrupted. Check whether the change applied before retrying.'))
|
||||
}
|
||||
pending.set(id, {resolve, reject, signal: request.signal, abort})
|
||||
request.signal.addEventListener('abort', abort, {once: true})
|
||||
if (request.signal.aborted) { abort(); return }
|
||||
StarPilotBLE.request(id, JSON.stringify({method: request.method, path: url.pathname + url.search,
|
||||
headers: Object.fromEntries(request.headers), body: btoa(body)}))
|
||||
})
|
||||
}
|
||||
})()
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
object AppInstallPolicy {
|
||||
const val MAX_APK_BYTES = 100L * 1024 * 1024
|
||||
private const val APK_TYPE = "application/vnd.android.package-archive"
|
||||
|
||||
fun accepts(status: Int, contentType: String?, contentLength: Long): Boolean =
|
||||
status == 200 && contentType?.substringBefore(';')?.trim()?.equals(APK_TYPE, ignoreCase = true) == true &&
|
||||
contentLength in 1..MAX_APK_BYTES
|
||||
|
||||
fun copyExact(input: InputStream, output: OutputStream, expected: Long) {
|
||||
require(expected in 1..MAX_APK_BYTES)
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
require(total <= expected) { "The update was larger than advertised" }
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
require(total == expected) { "The update download was incomplete" }
|
||||
}
|
||||
}
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageInstaller
|
||||
import android.net.Network
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/** Downloads a local, authenticated APK directly into Android's package installer. */
|
||||
object AppInstaller {
|
||||
const val ACTION = "link.firestar.companion.APP_INSTALL_STATUS"
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val installing = AtomicBoolean()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
fun start(context: Context, network: Network, origin: String): Boolean {
|
||||
if (!installing.compareAndSet(false, true)) return false
|
||||
val app = context.applicationContext
|
||||
Toast.makeText(app, "Downloading app update…", Toast.LENGTH_SHORT).show()
|
||||
executor.execute {
|
||||
try {
|
||||
downloadAndCommit(app, network, origin)
|
||||
} catch (error: Exception) {
|
||||
installing.set(false)
|
||||
main.post { Toast.makeText(app, "Update failed: ${error.message ?: "download unavailable"}", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun finished() { installing.set(false) }
|
||||
|
||||
private fun sessionCookie(network: Network, origin: String): String {
|
||||
val connection = network.openConnection(URL("$origin/api/auth/session")) as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 5000
|
||||
connection.readTimeout = 5000
|
||||
connection.instanceFollowRedirects = false
|
||||
check(connection.responseCode == 200) { "Galaxy authentication failed" }
|
||||
val body = connection.inputStream.bufferedReader().use { it.readText() }
|
||||
val status = JSONObject(body)
|
||||
check(status.optBoolean("authenticated") && status.optBoolean("localAccess")) { "Connect to Galaxy locally to update" }
|
||||
return connection.getHeaderField("Set-Cookie")?.substringBefore(';') ?: error("Galaxy session unavailable")
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
private fun downloadAndCommit(context: Context, network: Network, origin: String) {
|
||||
require(Networks.localOrigin(origin) == origin) { "Invalid Galaxy address" }
|
||||
val connection = network.openConnection(URL("$origin/app.apk")) as HttpURLConnection
|
||||
var sessionId = -1
|
||||
var committed = false
|
||||
try {
|
||||
connection.connectTimeout = 5000
|
||||
connection.readTimeout = 30000
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.setRequestProperty("Cookie", sessionCookie(network, origin))
|
||||
connection.setRequestProperty("Accept", "application/vnd.android.package-archive")
|
||||
val status = connection.responseCode
|
||||
val length = connection.contentLengthLong
|
||||
check(AppInstallPolicy.accepts(status, connection.contentType, length)) { "Invalid update response" }
|
||||
|
||||
val installer = context.packageManager.packageInstaller
|
||||
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||
setAppPackageName(context.packageName)
|
||||
setSize(length)
|
||||
setOriginatingUri(Uri.parse("$origin/app.apk"))
|
||||
if (Build.VERSION.SDK_INT >= 31) setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_REQUIRED)
|
||||
if (Build.VERSION.SDK_INT >= 33) setPackageSource(PackageInstaller.PACKAGE_SOURCE_DOWNLOADED_FILE)
|
||||
}
|
||||
sessionId = installer.createSession(params)
|
||||
installer.openSession(sessionId).use { session ->
|
||||
session.openWrite("base.apk", 0, length).use { output ->
|
||||
connection.inputStream.use { input -> AppInstallPolicy.copyExact(input, output, length) }
|
||||
session.fsync(output)
|
||||
}
|
||||
val callback = Intent(context, AppInstallReceiver::class.java).setAction(ACTION)
|
||||
val flags = PendingIntent.FLAG_UPDATE_CURRENT or
|
||||
(if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0)
|
||||
val result = PendingIntent.getBroadcast(context, sessionId, callback, flags)
|
||||
session.commit(result.intentSender)
|
||||
committed = true
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
if (!committed && sessionId >= 0) runCatching { context.packageManager.packageInstaller.abandonSession(sessionId) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AppInstallReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != AppInstaller.ACTION) return
|
||||
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
|
||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||
val confirmation = if (Build.VERSION.SDK_INT >= 33) {
|
||||
intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(Intent.EXTRA_INTENT) as? Intent
|
||||
}
|
||||
if (confirmation == null) {
|
||||
AppInstaller.finished()
|
||||
Toast.makeText(context, "Android could not open the update confirmation", Toast.LENGTH_LONG).show()
|
||||
} else runCatching {
|
||||
confirmation.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
context.startActivity(confirmation)
|
||||
}.onFailure {
|
||||
AppInstaller.finished()
|
||||
Toast.makeText(context, "Android could not open the update confirmation", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
PackageInstaller.STATUS_SUCCESS -> AppInstaller.finished()
|
||||
else -> {
|
||||
AppInstaller.finished()
|
||||
val detail = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)?.take(160)
|
||||
Toast.makeText(context, detail?.let { "Update failed: $it" } ?: "Update failed (Android status $status)", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.widget.Toast
|
||||
|
||||
/** Package replacement kills the old process; Android delivers this to the new APK. */
|
||||
class AppUpdateCompletion : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
val prefs = context.getSharedPreferences("companion", Context.MODE_PRIVATE)
|
||||
// The user may already have reopened the new version from Android's installer.
|
||||
if (prefs.getInt("lastOpenedAppCode", -1) == BuildConfig.VERSION_CODE) return
|
||||
prefs.edit().putInt("completedAppCode", BuildConfig.VERSION_CODE).apply()
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(CHANNEL, "App update completed", NotificationManager.IMPORTANCE_HIGH))
|
||||
if (!manager.areNotificationsEnabled() ||
|
||||
(Build.VERSION.SDK_INT >= 33 && context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED)) return
|
||||
val open = PendingIntent.getActivity(context, NOTIFICATION, Intent(context, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
manager.notify(NOTIFICATION, Notification.Builder(context, CHANNEL)
|
||||
.setSmallIcon(android.R.drawable.stat_sys_download_done)
|
||||
.setContentTitle("StarPilot update installed")
|
||||
.setContentText("Version ${BuildConfig.VERSION_NAME} is ready. Tap to reopen StarPilot.")
|
||||
.setContentIntent(open).setAutoCancel(true)
|
||||
.addAction(Notification.Action.Builder(null, "Reopen", open).build()).build())
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL = "app_update_completed"
|
||||
private const val NOTIFICATION = 3
|
||||
|
||||
fun opened(context: Context) {
|
||||
val prefs = context.getSharedPreferences("companion", Context.MODE_PRIVATE)
|
||||
if (prefs.getInt("completedAppCode", -1) == BuildConfig.VERSION_CODE) {
|
||||
Toast.makeText(context, "Updated to StarPilot ${BuildConfig.VERSION_NAME}", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
prefs.edit().putInt("lastOpenedAppCode", BuildConfig.VERSION_CODE).remove("completedAppCode").apply()
|
||||
context.getSystemService(NotificationManager::class.java).cancel(NOTIFICATION)
|
||||
}
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobService
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Future
|
||||
|
||||
class AppUpdateJob : JobService() {
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var active: JobParameters? = null
|
||||
private var task: Future<*>? = null
|
||||
|
||||
override fun onStartJob(params: JobParameters): Boolean {
|
||||
active = params
|
||||
task = executor.submit {
|
||||
runCatching { AppUpdates.check(applicationContext) }
|
||||
handler.post { if (active === params) { active = null; jobFinished(params, false) } }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onStopJob(params: JobParameters): Boolean {
|
||||
active = null
|
||||
task?.cancel(true)
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
active = null
|
||||
executor.shutdownNow()
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
object AppUpdatePolicy {
|
||||
/** Android 12 has no runtime notification permission; Android 13 introduced it. */
|
||||
fun notificationsAllowed(sdk: Int, appEnabled: Boolean, channelEnabled: Boolean, permissionGranted: Boolean): Boolean =
|
||||
appEnabled && channelEnabled && (sdk < 33 || permissionGranted)
|
||||
|
||||
fun newerVersion(available: String, installed: String): Boolean {
|
||||
fun parts(version: String): List<Long>? {
|
||||
if (!Regex("[0-9]+(?:\\.[0-9]+){1,3}").matches(version)) return null
|
||||
return version.split('.').map { it.toLongOrNull() ?: return null }
|
||||
}
|
||||
val next = parts(available) ?: return false
|
||||
val current = parts(installed) ?: return false
|
||||
for (index in 0 until maxOf(next.size, current.size)) {
|
||||
val comparison = (next.getOrElse(index) { 0L }).compareTo(current.getOrElse(index) { 0L })
|
||||
if (comparison != 0) return comparison > 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun shouldNotify(available: String, installed: String, appAvailable: Boolean, notificationsEnabled: Boolean,
|
||||
lastNotified: String): Boolean =
|
||||
appAvailable && notificationsEnabled && available != lastNotified && newerVersion(available, installed)
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.Manifest
|
||||
import android.app.*
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobScheduler
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.os.Build
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object AppUpdates {
|
||||
private const val CHANNEL = "app_updates"
|
||||
private const val NOTIFICATION = 2
|
||||
private const val JOB = 2
|
||||
const val ORIGIN_EXTRA = "updateOrigin"
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val checking = AtomicBoolean()
|
||||
private val notificationLock = Any()
|
||||
|
||||
fun initialize(context: Context) {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(CHANNEL, "App updates", NotificationManager.IMPORTANCE_HIGH).apply {
|
||||
description = "A notification when your comma has a newer StarPilot Android app"
|
||||
})
|
||||
// Remove an old update notification after that version has been installed.
|
||||
manager.activeNotifications.firstOrNull { it.id == NOTIFICATION }?.let {
|
||||
if (!AppUpdatePolicy.newerVersion(it.notification.extras.getString("availableVersion", ""), BuildConfig.VERSION_NAME)) {
|
||||
manager.cancel(NOTIFICATION)
|
||||
}
|
||||
}
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
if (scheduler.getPendingJob(JOB) == null) {
|
||||
val job = JobInfo.Builder(JOB, ComponentName(context, AppUpdateJob::class.java))
|
||||
.setPeriodic(TimeUnit.MINUTES.toMillis(15)).setPersisted(true)
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
// Galaxy's hotspot can lack internet/validation; it is still usable for updates.
|
||||
job.setRequiredNetwork(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED).build())
|
||||
}
|
||||
scheduler.schedule(job.build())
|
||||
}
|
||||
}
|
||||
|
||||
fun checkAsync(context: Context) {
|
||||
if (!checking.compareAndSet(false, true)) return
|
||||
val app = context.applicationContext
|
||||
executor.execute { try { runCatching { check(app) } } finally { checking.set(false) } }
|
||||
}
|
||||
|
||||
/** Runs on a worker thread, always through the Wi-Fi network, independent of mobile-data sharing. */
|
||||
fun check(context: Context) {
|
||||
val prefs = context.getSharedPreferences("companion", Context.MODE_PRIVATE)
|
||||
val wifi = Networks.wifi(context) ?: Networks.wifi(context, false) ?: return
|
||||
val origin = if (Networks.wifi(context) != null) Networks.ORIGIN else
|
||||
Networks.localOrigin(prefs.getString("host", "") ?: "")?.takeIf { it != Networks.ORIGIN } ?: return
|
||||
// Screens are static files on comma, so refresh them even before the session check.
|
||||
GalaxyUpdates.refreshAsync(context, wifi.first, origin)
|
||||
val session = request(wifi.first, origin, "/api/auth/session")
|
||||
if (!session.first.optBoolean("authenticated") || !session.first.optBoolean("localAccess")) return
|
||||
val status = request(wifi.first, origin, "/api/companion/status", session.second).first
|
||||
if (Thread.currentThread().isInterrupted) return
|
||||
val available = status.optString("shippedVersion")
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
synchronized(notificationLock) {
|
||||
val allowed = AppUpdatePolicy.notificationsAllowed(Build.VERSION.SDK_INT, manager.areNotificationsEnabled(),
|
||||
manager.getNotificationChannel(CHANNEL)?.importance != NotificationManager.IMPORTANCE_NONE,
|
||||
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED)
|
||||
if (!AppUpdatePolicy.shouldNotify(available, BuildConfig.VERSION_NAME, status.optBoolean("appAvailable"), allowed,
|
||||
prefs.getString("notifiedAppVersion", "") ?: "")) return
|
||||
val open = PendingIntent.getActivity(context, NOTIFICATION,
|
||||
Intent(context, MainActivity::class.java).putExtra(ORIGIN_EXTRA, origin),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val notification = Notification.Builder(context, CHANNEL).setSmallIcon(android.R.drawable.stat_sys_download_done)
|
||||
.setContentTitle("StarPilot app update available")
|
||||
.setContentText("Version $available is ready. Tap to open Galaxy and update the app.")
|
||||
.setContentIntent(open).setAutoCancel(true)
|
||||
.addExtras(android.os.Bundle().apply { putString("availableVersion", available) }).build()
|
||||
manager.notify(NOTIFICATION, notification)
|
||||
// Record only after posting; denied permission or a blocked channel must not consume the alert.
|
||||
prefs.edit().putString("notifiedAppVersion", available).apply()
|
||||
}
|
||||
}
|
||||
|
||||
private fun request(network: Network, origin: String, path: String, cookie: String = ""): Pair<JSONObject, String> {
|
||||
val connection = network.openConnection(URL(origin + path)) as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 3000; connection.readTimeout = 3000
|
||||
connection.instanceFollowRedirects = false
|
||||
if (cookie.isNotEmpty()) connection.setRequestProperty("Cookie", cookie)
|
||||
require(connection.responseCode == 200) { "Galaxy unavailable" }
|
||||
val body = connection.inputStream.bufferedReader().use { it.readText() }
|
||||
return JSONObject(body) to (connection.getHeaderField("Set-Cookie")?.substringBefore(';') ?: "")
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
-199
@@ -1,199 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.*
|
||||
import android.bluetooth.le.*
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.ParcelUuid
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** comma refused GATT access: it has no paired phones, or not this one. */
|
||||
class GattDenied(status: Int) : IOException("Bluetooth access denied ($status)")
|
||||
/** The link works but comma never answered the authenticated check: it no longer knows this phone's key. */
|
||||
class PairingNotRecognized(message: String) : IOException(message)
|
||||
private class ResponseTimeout : IOException("Bluetooth response timed out. Check the result before retrying a change.")
|
||||
|
||||
/** Serialized GATT operations; a failed mutation is never replayed. Call from a worker thread. */
|
||||
@SuppressLint("MissingPermission")
|
||||
/** [hello] ({"name", "replaces"}) is sent once with the first request so comma can label this phone and drop its old key. */
|
||||
class BleTransport(context: Context, private val key: ByteArray?, private val hello: JSONObject? = null) : Closeable {
|
||||
/** Reports what the connection is doing, so a slow pairing shows where it waits. */
|
||||
@Volatile var onPhase: (String) -> Unit = {}
|
||||
private val context: Context = context.applicationContext
|
||||
companion object {
|
||||
fun uuid(part: String): UUID = UUID.fromString("bd49000$part-6dc1-4de7-a7d0-6cdb441f7650")
|
||||
// comma keeps one session per phone, so every sender shares the newest connection.
|
||||
@SuppressLint("StaticFieldLeak") @Volatile var active: BleTransport? = null
|
||||
private set
|
||||
private val connecting = java.util.concurrent.atomic.AtomicInteger()
|
||||
val busy get() = connecting.get() > 0
|
||||
}
|
||||
val open get() = !closed && session.isNotEmpty()
|
||||
private data class Event(val kind: String, val status: Int, val data: ByteArray = byteArrayOf())
|
||||
private val events = LinkedBlockingQueue<Event>()
|
||||
@Volatile private var gatt: BluetoothGatt? = null
|
||||
@Volatile private var closed = false
|
||||
private var session = ""
|
||||
private var challenge = ByteArray(0)
|
||||
private var counter = 0L
|
||||
private var packetSize = 20
|
||||
private val callback = object : BluetoothGattCallback() {
|
||||
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, state: Int) {
|
||||
events.offer(Event(if (state == BluetoothProfile.STATE_CONNECTED) "connect" else "disconnect", status))
|
||||
}
|
||||
override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) { events.offer(Event("mtu", status, ByteBuffer.allocate(4).putInt(mtu).array())) }
|
||||
override fun onServicesDiscovered(g: BluetoothGatt, status: Int) { events.offer(Event("services", status)) }
|
||||
@Deprecated("Pre Android 13 callback") override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, status: Int) {
|
||||
if (Build.VERSION.SDK_INT < 33) events.offer(Event("read", status, c.value ?: byteArrayOf()))
|
||||
}
|
||||
override fun onCharacteristicRead(g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray, status: Int) {
|
||||
events.offer(Event("read", status, value.copyOf()))
|
||||
}
|
||||
override fun onCharacteristicWrite(g: BluetoothGatt, c: BluetoothGattCharacteristic, status: Int) { events.offer(Event("write", status)) }
|
||||
}
|
||||
private fun await(kind: String, seconds: Long = 12): ByteArray {
|
||||
val event = events.poll(seconds, TimeUnit.SECONDS) ?: throw IOException("Bluetooth timed out. Reconnect before retrying; a change may already have applied.")
|
||||
if (!closed && event.kind == kind && event.status in setOf(5, 8, 15)) throw GattDenied(event.status)
|
||||
if (closed || event.kind != kind || event.status != BluetoothGatt.GATT_SUCCESS) throw IOException("Bluetooth disconnected. Check the result before retrying a change.")
|
||||
return event.data
|
||||
}
|
||||
private fun characteristic(part: String) = gatt?.getService(uuid("1"))?.getCharacteristic(uuid(part)) ?: throw IOException("Galaxy Bluetooth service unavailable")
|
||||
private fun read(part: String): ByteArray {
|
||||
if (gatt?.readCharacteristic(characteristic(part)) != true) throw IOException("Bluetooth read unavailable")
|
||||
return await("read")
|
||||
}
|
||||
private fun write(value: ByteArray) {
|
||||
val g = gatt ?: throw IOException("Bluetooth disconnected")
|
||||
val c = characteristic("2")
|
||||
val sent = if (Build.VERSION.SDK_INT >= 33) g.writeCharacteristic(c, value, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) == BluetoothStatusCodes.SUCCESS
|
||||
else { c.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT; c.value = value; g.writeCharacteristic(c) }
|
||||
if (!sent) throw IOException("Bluetooth write unavailable")
|
||||
await("write")
|
||||
}
|
||||
/** Returns the authenticated device address so the next connection can skip scanning. */
|
||||
@Synchronized fun connect(preferredAddress: String? = null): String {
|
||||
check(!closed)
|
||||
connecting.incrementAndGet()
|
||||
try { return connectOnce(preferredAddress) } finally { connecting.decrementAndGet() }
|
||||
}
|
||||
private fun connectOnce(preferredAddress: String?): String {
|
||||
val device = try { linkUp(preferredAddress) } catch (e: GattDenied) {
|
||||
throw PairingNotRecognized("comma has no paired phone matching this one")
|
||||
}
|
||||
try {
|
||||
// Authenticate before exposing cached controls. Do not trust the advertised device name.
|
||||
val health = JSONObject().put("method", "GET").put("path", "/_bridge/health").apply { hello?.let { put("phone", it) } }
|
||||
val response = try { request(health, 20) } catch (e: ResponseTimeout) {
|
||||
throw PairingNotRecognized("comma didn't recognize this phone's pairing")
|
||||
}
|
||||
if (response.getInt("status") != 200) throw IOException("Galaxy Bluetooth authentication failed")
|
||||
val previous = active
|
||||
active = this
|
||||
if (previous !== this) previous?.close()
|
||||
return device.address
|
||||
} catch (e: Exception) { close(); throw e }
|
||||
}
|
||||
/** Scans, connects and reads the session challenge; nothing is authenticated yet. */
|
||||
private fun linkUp(preferredAddress: String?): BluetoothDevice {
|
||||
val adapter = context.getSystemService(BluetoothManager::class.java)?.adapter ?: throw IOException("Bluetooth is unavailable")
|
||||
if (!adapter.isEnabled) throw IOException("Enable Bluetooth on your phone and comma")
|
||||
val remembered = preferredAddress?.let { runCatching { adapter.getRemoteDevice(it) }.getOrNull() }
|
||||
val device = remembered ?: run {
|
||||
onPhase("Looking for comma over Bluetooth…")
|
||||
val scanner = adapter.bluetoothLeScanner ?: throw IOException("Bluetooth scanner unavailable")
|
||||
val found = LinkedBlockingQueue<BluetoothDevice>()
|
||||
val scan = object : ScanCallback() {
|
||||
override fun onScanResult(type: Int, result: ScanResult) { found.offer(result.device) }
|
||||
override fun onScanFailed(code: Int) { events.offer(Event("scan-failed", code)) }
|
||||
}
|
||||
scanner.startScan(listOf(ScanFilter.Builder().setServiceUuid(ParcelUuid(uuid("1"))).build()),
|
||||
ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), scan)
|
||||
try { found.poll(12, TimeUnit.SECONDS) } finally { scanner.stopScan(scan) }
|
||||
?: throw IOException("No Galaxy Bluetooth bridge found. Enable Bluetooth and install the bridge on comma.")
|
||||
}
|
||||
if (closed) throw IOException("Connection canceled")
|
||||
events.clear()
|
||||
onPhase("Found comma. Connecting…")
|
||||
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
|
||||
try {
|
||||
await("connect", if (remembered != null) 4 else 12)
|
||||
onPhase("Checking comma’s Bluetooth service…")
|
||||
if (gatt?.discoverServices() != true) throw IOException("Bluetooth discovery failed")
|
||||
await("services")
|
||||
if (gatt?.requestMtu(517) == true) packetSize = (ByteBuffer.wrap(await("mtu")).int - 3).coerceIn(20, 512)
|
||||
onPhase("Reading comma’s secure pairing challenge…")
|
||||
val info = read("4")
|
||||
require(info.size == 17 && info[0].toInt() == 1)
|
||||
challenge = info.copyOfRange(1, 17)
|
||||
session = info.drop(1).joinToString("") { "%02x".format(it.toInt() and 255) }
|
||||
return device
|
||||
} catch (e: Exception) { close(); throw e }
|
||||
}
|
||||
/** Asks the comma whose pairing window is open for a key. Returns the session challenge and comma's reply. */
|
||||
@Synchronized fun claim(body: ByteArray): Pair<ByteArray, ByteArray> {
|
||||
check(!closed)
|
||||
connecting.incrementAndGet()
|
||||
try {
|
||||
try { linkUp(null) } catch (e: GattDenied) {
|
||||
throw IOException("comma's pairing window isn't open. Open Pair phone on comma first (Settings > Bluetooth > Pair phone), then try again.")
|
||||
}
|
||||
onPhase("Pairing: sending this phone’s request to comma…")
|
||||
val frame = ByteBuffer.allocate(4 + body.size).putInt(body.size).put(body).array()
|
||||
for (packet in BleWire.packets(frame, packetSize)) write(packet)
|
||||
onPhase("Pairing: waiting for comma’s secure reply…")
|
||||
val assembler = BleWire.Assembler()
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20)
|
||||
while (System.nanoTime() < deadline) {
|
||||
val packet = read("3")
|
||||
if (packet.contentEquals(byteArrayOf(0))) { Thread.sleep(30); continue }
|
||||
val result = assembler.add(packet)
|
||||
if (result != null) {
|
||||
onPhase("Pairing: receiving comma’s secure reply…")
|
||||
write(ByteBuffer.allocate(5).put(2).put(packet, 1, 4).array())
|
||||
return challenge to result
|
||||
}
|
||||
}
|
||||
throw IOException("comma didn't answer. Open Pair phone on comma first (Settings > Bluetooth > Pair phone) and keep it open, then tap Add Bluetooth Phone Pairing again.")
|
||||
} catch (e: Exception) { close(); throw e } finally { connecting.decrementAndGet() }
|
||||
}
|
||||
@Synchronized fun request(value: JSONObject, deadlineSeconds: Long = 90): JSONObject {
|
||||
check(!closed && session.isNotEmpty())
|
||||
val id = UUID.randomUUID().toString()
|
||||
val count = ++counter
|
||||
val request = JSONObject(value.toString()).put("id", id).put("session", session).put("counter", count).put("responseCodec", 2).put("responseFlow", "read-stream")
|
||||
// Upstream read-stream flow acknowledges once after authenticated reassembly.
|
||||
try {
|
||||
for (packet in BleWire.packets(BleWire.seal(request.toString().toByteArray(), key ?: throw IOException("Not paired")), packetSize)) write(packet)
|
||||
val assembler = BleWire.Assembler()
|
||||
val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(deadlineSeconds)
|
||||
while (System.nanoTime() < deadline) {
|
||||
val packet = read("3")
|
||||
if (packet.contentEquals(byteArrayOf(0))) { Thread.sleep(30); continue }
|
||||
val result = assembler.add(packet)
|
||||
if (result != null) {
|
||||
val decoded = BleWire.decode(result, key ?: throw IOException("Not paired"))
|
||||
val response = JSONObject(String(decoded.json, Charsets.UTF_8))
|
||||
decoded.body?.let { require(!response.has("body")); response.put("body", java.util.Base64.getEncoder().encodeToString(it)) }
|
||||
require(response.getString("id") == id && response.getString("session") == session && response.getLong("counter") == count)
|
||||
write(ByteBuffer.allocate(5).put(2).put(packet, 1, 4).array())
|
||||
return response
|
||||
}
|
||||
}
|
||||
throw ResponseTimeout()
|
||||
} catch (e: Exception) { close(); throw e }
|
||||
}
|
||||
override fun close() {
|
||||
closed = true
|
||||
if (active === this) active = null
|
||||
val old = gatt; gatt = null
|
||||
old?.disconnect(); old?.close()
|
||||
events.offer(Event("disconnect", -1))
|
||||
}
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.security.SecureRandom
|
||||
import java.util.zip.Inflater
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** Byte-compatible Galaxy BLE v1. Requests use codec 0; responses support all three codecs. */
|
||||
object BleWire {
|
||||
const val MAX = 2 * 1024 * 1024
|
||||
fun seal(json: ByteArray, key: ByteArray, direction: String = "request", nonce: ByteArray = ByteArray(12).also { SecureRandom().nextBytes(it) }): ByteArray {
|
||||
require(json.size in 1..MAX && key.size == 32 && nonce.size == 12)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
cipher.updateAAD("galaxy-ble-v1/$direction".toByteArray())
|
||||
val encoded = ByteBuffer.allocate(5 + json.size).put(0).putInt(json.size).put(json).array()
|
||||
val data = nonce + cipher.doFinal(encoded)
|
||||
require(data.size <= MAX)
|
||||
return ByteBuffer.allocate(4 + data.size).putInt(data.size).put(data).array()
|
||||
}
|
||||
data class Message(val json: ByteArray, val body: ByteArray? = null)
|
||||
fun open(data: ByteArray, key: ByteArray, direction: String = "response"): ByteArray = decode(data, key, direction).json
|
||||
fun decode(data: ByteArray, key: ByteArray, direction: String = "response"): Message {
|
||||
require(data.size in 33..MAX && key.size == 32)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, data.copyOfRange(0, 12)))
|
||||
cipher.updateAAD("galaxy-ble-v1/$direction".toByteArray())
|
||||
val encoded = cipher.doFinal(data.copyOfRange(12, data.size))
|
||||
require(encoded.size >= 5)
|
||||
val size = ByteBuffer.wrap(encoded, 1, 4).int
|
||||
require(size in 1..MAX)
|
||||
if (encoded[0].toInt() == 0) return Message(encoded.copyOfRange(5, encoded.size).also { require(it.size == size) })
|
||||
require(encoded[0].toInt() in 1..2)
|
||||
val inflater = Inflater(true)
|
||||
try {
|
||||
inflater.setInput(encoded, 5, encoded.size - 5)
|
||||
val result = ByteArray(size + 1)
|
||||
var count = 0
|
||||
while (!inflater.finished() && count < result.size) {
|
||||
val n = inflater.inflate(result, count, result.size - count)
|
||||
require(n > 0 || inflater.finished())
|
||||
count += n
|
||||
}
|
||||
require(inflater.finished() && inflater.remaining == 0 && count == size)
|
||||
if (encoded[0].toInt() == 2) {
|
||||
require(size >= 4)
|
||||
val metadata = ByteBuffer.wrap(result, 0, 4).int
|
||||
require(metadata in 1..(size - 4) && size - 4 - metadata <= 1024 * 1024)
|
||||
return Message(result.copyOfRange(4, 4 + metadata), result.copyOfRange(4 + metadata, size))
|
||||
}
|
||||
return Message(result.copyOf(size))
|
||||
} finally { inflater.end() }
|
||||
}
|
||||
fun packets(frame: ByteArray, size: Int): List<ByteArray> {
|
||||
require(size in 20..512 && frame.size <= MAX + 4)
|
||||
return (frame.indices step (size - 5)).mapIndexed { index, start ->
|
||||
val count = minOf(size - 5, frame.size - start)
|
||||
ByteBuffer.allocate(5 + count).put(1).putInt(index).put(frame, start, count).array()
|
||||
}
|
||||
}
|
||||
class Assembler {
|
||||
private val bytes = ByteArrayOutputStream()
|
||||
private var sequence = 0
|
||||
private var length: Int? = null
|
||||
fun add(packet: ByteArray): ByteArray? {
|
||||
require(packet.size >= 6 && packet[0].toInt() == 1 && ByteBuffer.wrap(packet, 1, 4).int == sequence++)
|
||||
require(bytes.size() + packet.size - 5 <= MAX + 4)
|
||||
bytes.write(packet, 5, packet.size - 5)
|
||||
if (length == null && bytes.size() >= 4) length = ByteBuffer.wrap(bytes.toByteArray(), 0, 4).int
|
||||
val expected = length ?: return null
|
||||
require(expected in 28..MAX && bytes.size() <= expected + 4)
|
||||
return if (bytes.size() == expected + 4) bytes.toByteArray().copyOfRange(4, expected + 4) else null
|
||||
}
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
/** Explicit opt-in: the foreground service waits for a Galaxy Wi-Fi address. */
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
|
||||
val prefs = context.getSharedPreferences("companion", Context.MODE_PRIVATE)
|
||||
if (prefs.getBoolean("autoStart", false) && prefs.getBoolean("enabled", false)) {
|
||||
context.startForegroundService(Intent(context, UplinkService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import java.math.BigInteger
|
||||
import java.security.AlgorithmParameters
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.PrivateKey
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.ECParameterSpec
|
||||
import java.security.spec.ECPoint
|
||||
import java.security.spec.ECPrivateKeySpec
|
||||
import java.security.spec.ECPublicKeySpec
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyAgreement
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* Pairing with comma's open window: this phone sends a P-256 public key and gets its own key back, sealed under
|
||||
* an ECDH-derived key. See galaxy_bluetooth/README.md ("Pairing a phone") for the byte layout.
|
||||
*/
|
||||
object ClaimPairing {
|
||||
data class Claim(val key: ByteArray, val id: String, val adapterAddress: String, val adapterName: String)
|
||||
|
||||
private val REQUEST_MAGIC = "GCL1".toByteArray()
|
||||
private val REPLY_MAGIC = "GCR1".toByteArray()
|
||||
private val INFO = "galaxy-claim-v1".toByteArray()
|
||||
private val AAD = "galaxy-claim-v1/reply".toByteArray()
|
||||
private val HEX64 = Regex("[0-9a-f]{64}")
|
||||
private val PHONE_ID = Regex("[0-9a-f]{8}")
|
||||
private val ADDRESS = Regex("(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){5}")
|
||||
private const val POINT = 65
|
||||
|
||||
private val curve: ECParameterSpec by lazy {
|
||||
AlgorithmParameters.getInstance("EC").apply { init(ECGenParameterSpec("secp256r1")) }.getParameterSpec(ECParameterSpec::class.java)
|
||||
}
|
||||
|
||||
fun newKeyPair(): KeyPair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()
|
||||
|
||||
/** The 65-byte uncompressed point: 0x04 | X | Y. */
|
||||
fun point(key: ECPublicKey): ByteArray {
|
||||
fun fixed(value: BigInteger) = value.toByteArray().let { bytes ->
|
||||
when {
|
||||
bytes.size == 32 -> bytes
|
||||
bytes.size == 33 && bytes[0].toInt() == 0 -> bytes.copyOfRange(1, 33)
|
||||
bytes.size < 32 -> ByteArray(32 - bytes.size) + bytes
|
||||
else -> throw IllegalArgumentException("Invalid coordinate")
|
||||
}
|
||||
}
|
||||
return byteArrayOf(4) + fixed(key.w.affineX) + fixed(key.w.affineY)
|
||||
}
|
||||
|
||||
fun request(publicPoint: ByteArray, name: String): ByteArray {
|
||||
require(publicPoint.size == POINT && publicPoint[0].toInt() == 4)
|
||||
return REQUEST_MAGIC + publicPoint + name.take(40).toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
|
||||
fun privateKey(scalar: BigInteger): PrivateKey = KeyFactory.getInstance("EC").generatePrivate(ECPrivateKeySpec(scalar, curve))
|
||||
|
||||
private fun publicKey(point: ByteArray): ECPublicKey {
|
||||
require(point.size == POINT && point[0].toInt() == 4)
|
||||
val x = BigInteger(1, point.copyOfRange(1, 33))
|
||||
val y = BigInteger(1, point.copyOfRange(33, 65))
|
||||
return KeyFactory.getInstance("EC").generatePublic(ECPublicKeySpec(ECPoint(x, y), curve)) as ECPublicKey
|
||||
}
|
||||
|
||||
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
|
||||
Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data)
|
||||
|
||||
/** ECDH on P-256 then HKDF-SHA256 (RFC 5869) with the session challenge as salt. */
|
||||
fun derive(privateKey: PrivateKey, peerPoint: ByteArray, challenge: ByteArray): ByteArray {
|
||||
val secret = KeyAgreement.getInstance("ECDH").apply { init(privateKey); doPhase(publicKey(peerPoint), true) }.generateSecret()
|
||||
require(secret.size == 32)
|
||||
return hmac(hmac(challenge, secret), INFO + byteArrayOf(1))
|
||||
}
|
||||
|
||||
/** Opens comma's reply. Throws when it is not for this request (wrong key, tampered, or not a claim reply). */
|
||||
fun open(reply: ByteArray, privateKey: PrivateKey, challenge: ByteArray): Claim {
|
||||
require(reply.size > 4 + POINT + 12 + 16 && reply.copyOfRange(0, 4).contentEquals(REPLY_MAGIC))
|
||||
val key = derive(privateKey, reply.copyOfRange(4, 4 + POINT), challenge)
|
||||
val nonce = reply.copyOfRange(4 + POINT, 4 + POINT + 12)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
|
||||
cipher.updateAAD(AAD)
|
||||
return parse(String(cipher.doFinal(reply, 4 + POINT + 12, reply.size - 4 - POINT - 12), Charsets.UTF_8))
|
||||
}
|
||||
|
||||
fun parse(json: String): Claim {
|
||||
val hex = stringField(json, "key") ?: throw IllegalArgumentException("No key in reply")
|
||||
require(HEX64.matches(hex))
|
||||
val id = stringField(json, "id").orEmpty()
|
||||
val address = stringField(json, "adapterAddress").orEmpty()
|
||||
return Claim(hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray(), if (PHONE_ID.matches(id)) id else "",
|
||||
if (ADDRESS.matches(address)) address.uppercase() else "", stringField(json, "adapterName").orEmpty().take(80))
|
||||
}
|
||||
|
||||
/** The value of a top-level string field in comma's flat JSON object, with escapes decoded. */
|
||||
internal fun stringField(json: String, name: String): String? {
|
||||
val start = json.indexOf("\"$name\":\"").takeIf { it >= 0 }?.plus(name.length + 4) ?: return null
|
||||
val out = StringBuilder()
|
||||
var i = start
|
||||
while (i < json.length) {
|
||||
when (val c = json[i]) {
|
||||
'"' -> return out.toString()
|
||||
'\\' -> {
|
||||
i++
|
||||
when (val e = json.getOrNull(i) ?: return null) {
|
||||
'n' -> out.append('\n'); 't' -> out.append('\t'); 'r' -> out.append('\r')
|
||||
'b' -> out.append('\b'); 'f' -> out.append('\u000c')
|
||||
'u' -> { out.append(json.substring(i + 1, minOf(i + 5, json.length)).toIntOrNull(16)?.toChar() ?: return null); i += 4 }
|
||||
else -> out.append(e)
|
||||
}
|
||||
}
|
||||
else -> out.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Asks the comma that has its pairing window open for a key. Blocks; call from a worker thread. */
|
||||
fun claim(transport: BleTransport, name: String): Claim {
|
||||
val pair = newKeyPair()
|
||||
val (challenge, reply) = transport.claim(request(point(pair.public as ECPublicKey), name))
|
||||
return open(reply, pair.private, challenge)
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
/** When this phone's Bluetooth bond with comma disappears, the app pairing should go with it. */
|
||||
object CommaBond {
|
||||
const val BOND_NONE = 10
|
||||
|
||||
/** A bond-state broadcast says comma's audio bond ended, for example after Forget in the phone's Bluetooth settings. */
|
||||
fun forgotten(remembered: String?, changed: String?, state: Int) =
|
||||
remembered != null && changed.equals(remembered, ignoreCase = true) && state == BOND_NONE
|
||||
|
||||
/** The saved audio bond is no longer among the phone's bonded devices (forgotten while the app was closed). */
|
||||
fun missing(remembered: String?, bonded: Set<String>) =
|
||||
remembered != null && bonded.none { it.equals(remembered, ignoreCase = true) }
|
||||
}
|
||||
-348
@@ -1,348 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.animation.ValueAnimator
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.*
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.graphics.drawable.RippleDrawable
|
||||
import android.text.InputType
|
||||
import android.text.TextUtils
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.animation.LinearInterpolator
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.*
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
/** Connections in the order Automatic tries them. */
|
||||
enum class Route(val title: String, val icon: Int) {
|
||||
GALAXY_WIFI("Galaxy Wi-Fi", R.drawable.ic_route_wifi),
|
||||
HOME_NETWORK("Home network", R.drawable.ic_route_lan),
|
||||
BLUETOOTH("Bluetooth", R.drawable.ic_route_bluetooth),
|
||||
}
|
||||
|
||||
enum class RouteState { IDLE, UNAVAILABLE, TRYING, FAILED, LIVE }
|
||||
|
||||
/** Galaxy web tokens, so the native screens hand off to the web app without a seam. */
|
||||
object Palette {
|
||||
const val SPACE = 0xFF070712.toInt()
|
||||
const val SURFACE = 0xFF110E1F.toInt()
|
||||
const val VIOLET = 0xFF9D72FF.toInt()
|
||||
const val VIOLET_SOFT = 0xFFC9B3FF.toInt()
|
||||
const val CYAN = 0xFF4DE8E8.toInt()
|
||||
const val ON = 0xFFF3F2F8.toInt()
|
||||
const val MUTED = 0xFF9D9BB8.toInt()
|
||||
const val ERROR = 0xFFFF5277.toInt()
|
||||
const val LINE = 0x1FFFFFFF
|
||||
fun of(state: RouteState) = when (state) {
|
||||
RouteState.IDLE -> ON
|
||||
RouteState.UNAVAILABLE -> MUTED
|
||||
RouteState.TRYING -> VIOLET_SOFT
|
||||
RouteState.FAILED -> ERROR
|
||||
RouteState.LIVE -> CYAN
|
||||
}
|
||||
fun alpha(color: Int, alpha: Int) = (color and 0x00FFFFFF) or (alpha.coerceIn(0, 255) shl 24)
|
||||
val condensed: Typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
|
||||
val medium: Typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
|
||||
}
|
||||
|
||||
/** comma at the center, one tilted orbit per connection. The orbit being tried carries a moving comet. */
|
||||
class OrbitView(context: Context) : View(context) {
|
||||
private val dp = resources.displayMetrics.density
|
||||
private val states = Array(Route.entries.size) { RouteState.IDLE }
|
||||
private val icons = Route.entries.map { context.getDrawable(it.icon)!!.mutate() }
|
||||
private val core = BitmapFactory.decodeResource(resources, R.drawable.galaxy)
|
||||
private val tilt = floatArrayOf(-16f, 8f, -5f)
|
||||
private val reach = floatArrayOf(0.40f, 0.68f, 0.96f)
|
||||
private val anchor = floatArrayOf(200f, 330f, 105f)
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val corePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
private val dash = DashPathEffect(floatArrayOf(3 * dp, 5 * dp), 0f)
|
||||
private var glow: Shader? = null
|
||||
private var phase = 0f
|
||||
private val spin = ValueAnimator.ofFloat(0f, 1f).apply {
|
||||
duration = 2600; repeatCount = ValueAnimator.INFINITE; interpolator = LinearInterpolator()
|
||||
addUpdateListener { phase = it.animatedValue as Float; invalidate() }
|
||||
}
|
||||
|
||||
init { importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO } // The route rows carry the same information.
|
||||
|
||||
fun set(route: Route, state: RouteState) { states[route.ordinal] = state; updateMotion(); invalidate() }
|
||||
|
||||
private fun moving() = isAttachedToWindow && states.any { it == RouteState.TRYING } && ValueAnimator.areAnimatorsEnabled()
|
||||
private fun updateMotion() { if (moving()) { if (!spin.isStarted) spin.start() } else if (spin.isStarted) spin.cancel() }
|
||||
override fun onAttachedToWindow() { super.onAttachedToWindow(); updateMotion() }
|
||||
override fun onDetachedFromWindow() { spin.cancel(); super.onDetachedFromWindow() }
|
||||
|
||||
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
|
||||
val width = MeasureSpec.getSize(widthSpec)
|
||||
setMeasuredDimension(width, (width * 0.56f).roundToInt().coerceIn((190 * dp).roundToInt(), (260 * dp).roundToInt()))
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
glow = RadialGradient(w / 2f, h / 2f, 88 * dp, intArrayOf(0x599D72FF, 0x149D72FF, 0), floatArrayOf(0f, 0.45f, 1f), Shader.TileMode.CLAMP)
|
||||
val radius = 30 * dp
|
||||
val scale = radius * 2.5f / core.width
|
||||
corePaint.shader = BitmapShader(core, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP).apply {
|
||||
setLocalMatrix(Matrix().apply { setScale(scale, scale); postTranslate(w / 2f - core.width * scale / 2, h / 2f - core.height * scale / 2) })
|
||||
}
|
||||
}
|
||||
|
||||
private fun radiusX(i: Int) = (width / 2f - 24 * dp) * reach[i]
|
||||
private fun point(i: Int, degrees: Float): PointF {
|
||||
val rx = radiusX(i); val ry = rx * SQUASH
|
||||
val a = Math.toRadians(degrees.toDouble()); val t = Math.toRadians(tilt[i].toDouble())
|
||||
val x = rx * cos(a); val y = ry * sin(a)
|
||||
return PointF((width / 2f + x * cos(t) - y * sin(t)).toFloat(), (height / 2f + x * sin(t) + y * cos(t)).toFloat())
|
||||
}
|
||||
|
||||
private fun orbit(canvas: Canvas, i: Int, sweep: Float) {
|
||||
val state = states[i]
|
||||
stroke.strokeWidth = 1.2f * dp
|
||||
stroke.pathEffect = if (state == RouteState.UNAVAILABLE) dash else null
|
||||
stroke.color = when (state) {
|
||||
RouteState.UNAVAILABLE -> Palette.alpha(Color.WHITE, 36)
|
||||
RouteState.IDLE -> Palette.alpha(Color.WHITE, 46)
|
||||
else -> Palette.alpha(Palette.of(state), 130)
|
||||
}
|
||||
val rx = radiusX(i); val ry = rx * SQUASH; val cx = width / 2f; val cy = height / 2f
|
||||
canvas.save(); canvas.rotate(tilt[i], cx, cy)
|
||||
canvas.drawArc(RectF(cx - rx, cy - ry, cx + rx, cy + ry), 0f, sweep, false, stroke)
|
||||
canvas.restore()
|
||||
stroke.pathEffect = null
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val cx = width / 2f; val cy = height / 2f; val coreRadius = 30 * dp
|
||||
fill.shader = glow; canvas.drawCircle(cx, cy, 88 * dp, fill); fill.shader = null
|
||||
for (i in states.indices) orbit(canvas, i, 360f)
|
||||
for (i in states.indices) if (states[i] == RouteState.LIVE) {
|
||||
val p = point(i, anchor[i]); stroke.color = Palette.alpha(Palette.CYAN, 170); stroke.strokeWidth = 1.5f * dp
|
||||
canvas.drawLine(cx, cy, p.x, p.y, stroke)
|
||||
}
|
||||
canvas.drawCircle(cx, cy, coreRadius, corePaint)
|
||||
stroke.color = Palette.alpha(Color.WHITE, 60); stroke.strokeWidth = 1 * dp
|
||||
canvas.drawCircle(cx, cy, coreRadius, stroke)
|
||||
// Redraw the near half of each orbit so the rings pass in front of comma.
|
||||
for (i in states.indices) orbit(canvas, i, 180f)
|
||||
val animating = spin.isStarted
|
||||
for (i in states.indices) if (states[i] == RouteState.TRYING) {
|
||||
val head = anchor[i] + (if (animating) phase else 0.86f) * 360f
|
||||
for (k in 0 until 16) {
|
||||
val p = point(i, head - k * 3.2f)
|
||||
fill.color = Palette.alpha(Palette.VIOLET_SOFT, (235 * (1 - k / 16f)).roundToInt())
|
||||
canvas.drawCircle(p.x, p.y, (3.2f - k * 0.15f) * dp, fill)
|
||||
}
|
||||
}
|
||||
val nodeRadius = 19 * dp; val iconHalf = (9 * dp).roundToInt()
|
||||
for (i in states.indices) {
|
||||
val state = states[i]; val color = Palette.of(state); val p = point(i, anchor[i])
|
||||
fill.color = Palette.SPACE; canvas.drawCircle(p.x, p.y, nodeRadius, fill)
|
||||
fill.color = Palette.alpha(color, if (state == RouteState.UNAVAILABLE) 14 else 38); canvas.drawCircle(p.x, p.y, nodeRadius, fill)
|
||||
stroke.strokeWidth = 1.5f * dp; stroke.color = Palette.alpha(color, if (state == RouteState.UNAVAILABLE) 70 else 255)
|
||||
canvas.drawCircle(p.x, p.y, nodeRadius, stroke)
|
||||
if (state == RouteState.TRYING && animating) {
|
||||
stroke.color = Palette.alpha(color, ((1 - phase) * 150).roundToInt())
|
||||
canvas.drawCircle(p.x, p.y, nodeRadius + 12 * dp * phase, stroke)
|
||||
}
|
||||
icons[i].setTint(if (state == RouteState.UNAVAILABLE) Palette.alpha(Palette.MUTED, 150) else color)
|
||||
icons[i].setBounds(p.x.roundToInt() - iconHalf, p.y.roundToInt() - iconHalf, p.x.roundToInt() + iconHalf, p.y.roundToInt() + iconHalf)
|
||||
icons[i].draw(canvas)
|
||||
}
|
||||
}
|
||||
|
||||
companion object { const val SQUASH = 0.36f }
|
||||
}
|
||||
|
||||
/** The screen shown while not connected, and over the Galaxy page while it loads. */
|
||||
class ConnectScreen(private val activity: Activity, private val onRoute: (Route) -> Unit, onRetry: () -> Unit,
|
||||
onWifiSettings: () -> Unit, private val onAddress: (String) -> String?, onOptions: () -> Unit) {
|
||||
private val dp = activity.resources.displayMetrics.density
|
||||
private fun px(value: Number) = (value.toFloat() * dp).roundToInt()
|
||||
private val orbit = OrbitView(activity)
|
||||
private val headline = text(30f, Palette.ON, Palette.condensed).apply { setLineSpacing(0f, 0.95f) }
|
||||
private val detail = text(15f, Palette.MUTED).apply { setLineSpacing(px(3).toFloat(), 1f) }
|
||||
private val footer = text(13f, Palette.MUTED)
|
||||
private val states = mutableMapOf<Route, RouteState>()
|
||||
private val rows = mutableMapOf<Route, Row>()
|
||||
private val address = EditText(activity)
|
||||
private val addressRow = LinearLayout(activity)
|
||||
val view: ScrollView
|
||||
|
||||
private inner class Row(val route: Route) {
|
||||
val icon = ImageView(activity).apply { setImageResource(route.icon); scaleType = ImageView.ScaleType.CENTER_INSIDE }
|
||||
val title = text(16f, Palette.ON, Palette.medium).apply { text = route.title }
|
||||
val state = text(14f, Palette.MUTED, Palette.condensed)
|
||||
val spinner = ProgressBar(activity).apply { isIndeterminate = true; indeterminateTintList = ColorStateList.valueOf(Palette.VIOLET_SOFT); visibility = View.GONE }
|
||||
val view = LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL
|
||||
minimumHeight = px(68); setPadding(px(16), px(10), px(16), px(10))
|
||||
isClickable = true; isFocusable = true
|
||||
setOnClickListener { onRoute(route) }
|
||||
addView(icon, LinearLayout.LayoutParams(px(40), px(40)))
|
||||
addView(LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
addView(title); addView(state)
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = px(14) })
|
||||
addView(spinner, LinearLayout.LayoutParams(px(20), px(20)))
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val panel = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(px(20), px(4), px(20), px(24)) }
|
||||
panel.addView(orbit, LinearLayout.LayoutParams(-1, -2))
|
||||
panel.addView(headline, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(8) })
|
||||
panel.addView(detail, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(8) })
|
||||
|
||||
val list = LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
background = GradientDrawable().apply { cornerRadius = px(24).toFloat(); setColor(Palette.SURFACE); setStroke(px(1), Palette.LINE) }
|
||||
clipToOutline = true
|
||||
}
|
||||
Route.entries.forEachIndexed { index, route ->
|
||||
if (index > 0) list.addView(View(activity).apply { setBackgroundColor(Palette.LINE) },
|
||||
LinearLayout.LayoutParams(-1, px(1)).apply { marginStart = px(70) })
|
||||
val row = Row(route); rows[route] = row; list.addView(row.view)
|
||||
route(route, RouteState.IDLE, "")
|
||||
}
|
||||
panel.addView(list, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(22) })
|
||||
|
||||
panel.addView(text(16f, Palette.SPACE, Palette.medium).apply {
|
||||
text = "Try again"; gravity = Gravity.CENTER; isClickable = true; isFocusable = true
|
||||
background = RippleDrawable(ColorStateList.valueOf(0x40FFFFFF), GradientDrawable().apply { cornerRadius = px(26).toFloat(); setColor(Palette.VIOLET) }, null)
|
||||
setOnClickListener { onRetry() }
|
||||
}, LinearLayout.LayoutParams(-1, px(52)).apply { topMargin = px(20) })
|
||||
|
||||
val links = LinearLayout(activity).apply { orientation = LinearLayout.HORIZONTAL }
|
||||
links.addView(link("Wi-Fi settings", onWifiSettings), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
links.addView(link("Type an address") { toggleAddress() }, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
links.addView(link("More options", onOptions), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
panel.addView(links, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(6) })
|
||||
|
||||
address.apply {
|
||||
hint = "192.168.1.10"; setSingleLine(); textSize = 16f
|
||||
setTextColor(Palette.ON); setHintTextColor(Palette.alpha(Palette.MUTED, 170))
|
||||
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
|
||||
imeOptions = EditorInfo.IME_ACTION_GO
|
||||
contentDescription = "comma address on your network"
|
||||
background = GradientDrawable().apply { cornerRadius = px(16).toFloat(); setColor(Palette.SURFACE); setStroke(px(1), Palette.LINE) }
|
||||
setPadding(px(16), px(12), px(16), px(12))
|
||||
setOnEditorActionListener { _, action, _ -> if (action == EditorInfo.IME_ACTION_GO) { open(); true } else false }
|
||||
}
|
||||
addressRow.apply {
|
||||
orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL; visibility = View.GONE
|
||||
addView(address, LinearLayout.LayoutParams(0, -2, 1f))
|
||||
addView(text(15f, Palette.SPACE, Palette.medium).apply {
|
||||
text = "Open"; gravity = Gravity.CENTER; isClickable = true; isFocusable = true; setPadding(px(20), 0, px(20), 0)
|
||||
background = RippleDrawable(ColorStateList.valueOf(0x40FFFFFF), GradientDrawable().apply { cornerRadius = px(16).toFloat(); setColor(Palette.VIOLET) }, null)
|
||||
setOnClickListener { open() }
|
||||
}, LinearLayout.LayoutParams(-2, px(48)).apply { marginStart = px(10) })
|
||||
}
|
||||
panel.addView(addressRow, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(8) })
|
||||
panel.addView(footer, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(18) })
|
||||
|
||||
view = ScrollView(activity).apply {
|
||||
isFillViewport = true; setBackgroundColor(Palette.SPACE); clipToPadding = false
|
||||
addView(panel)
|
||||
setOnApplyWindowInsetsListener { v, insets ->
|
||||
v.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, insets.systemWindowInsetBottom); insets
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun text(size: Float, color: Int, face: Typeface? = null) = TextView(activity).apply {
|
||||
textSize = size; setTextColor(color); face?.let { typeface = it }
|
||||
}
|
||||
|
||||
private fun link(label: String, action: () -> Unit) = text(14f, Palette.VIOLET_SOFT, Palette.medium).apply {
|
||||
text = label; gravity = Gravity.CENTER; isClickable = true; isFocusable = true
|
||||
minHeight = px(48); setPadding(px(4), px(8), px(4), px(8))
|
||||
background = RippleDrawable(ColorStateList.valueOf(Palette.alpha(Palette.VIOLET, 60)), null, null)
|
||||
setOnClickListener { action() }
|
||||
}
|
||||
|
||||
private fun toggleAddress() {
|
||||
val show = addressRow.visibility != View.VISIBLE
|
||||
addressRow.visibility = if (show) View.VISIBLE else View.GONE
|
||||
if (show) {
|
||||
address.requestFocus()
|
||||
activity.getSystemService(android.view.inputmethod.InputMethodManager::class.java)?.showSoftInput(address, 0)
|
||||
view.post { view.smoothScrollTo(0, addressRow.bottom) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun open() { onAddress(address.text.toString())?.let { address.error = it } }
|
||||
|
||||
fun headline(text: String) { headline.text = text }
|
||||
fun detail(text: String) { detail.text = text }
|
||||
fun mode(transport: String?) {
|
||||
footer.text = when (transport) {
|
||||
"wifi" -> "Set to Wi-Fi and LAN only. Change this in More options."
|
||||
"bluetooth" -> "Set to Bluetooth only. Change this in More options."
|
||||
else -> "Automatic always checks Galaxy Wi-Fi and your home network before Bluetooth."
|
||||
}
|
||||
}
|
||||
fun route(route: Route, state: RouteState, text: String) {
|
||||
states[route] = state
|
||||
orbit.set(route, state)
|
||||
val row = rows[route] ?: return
|
||||
val color = Palette.of(state)
|
||||
row.state.text = text; row.state.setTextColor(color)
|
||||
row.state.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE
|
||||
row.spinner.visibility = if (state == RouteState.TRYING) View.VISIBLE else View.GONE
|
||||
row.icon.imageTintList = ColorStateList.valueOf(if (state == RouteState.UNAVAILABLE) Palette.MUTED else color)
|
||||
row.icon.background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(Palette.alpha(color, if (state == RouteState.UNAVAILABLE) 16 else 34)) }
|
||||
row.title.setTextColor(if (state == RouteState.UNAVAILABLE) Palette.MUTED else Palette.ON)
|
||||
row.view.background = RippleDrawable(ColorStateList.valueOf(Palette.alpha(Palette.VIOLET, 60)),
|
||||
if (state == RouteState.TRYING) GradientDrawable().apply { setColor(Palette.alpha(Palette.VIOLET, 28)) } else null,
|
||||
GradientDrawable().apply { setColor(Color.WHITE) })
|
||||
row.view.contentDescription = if (text.isEmpty()) route.title else "${route.title}, $text"
|
||||
}
|
||||
fun state(route: Route) = states[route]
|
||||
fun busy() = states.values.any { it == RouteState.TRYING }
|
||||
|
||||
/** Fade away to reveal the page underneath. */
|
||||
fun dismiss() {
|
||||
val remove = { (view.parent as? ViewGroup)?.removeView(view); Unit }
|
||||
if (ValueAnimator.areAnimatorsEnabled()) view.animate().alpha(0f).setDuration(240).withEndAction(remove).start() else remove()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Slim bar above live pages: which connection is in use, and a way to change it. */
|
||||
fun webBar(activity: Activity, route: Route, label: String, onConnections: () -> Unit): View {
|
||||
val dp = activity.resources.displayMetrics.density
|
||||
fun px(value: Number) = (value.toFloat() * dp).roundToInt()
|
||||
val bar = LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL
|
||||
minimumHeight = px(48); setPadding(px(16), 0, px(4), 0)
|
||||
addView(ImageView(activity).apply { setImageResource(route.icon); imageTintList = ColorStateList.valueOf(Palette.CYAN) },
|
||||
LinearLayout.LayoutParams(px(18), px(18)))
|
||||
addView(TextView(activity).apply {
|
||||
text = label; textSize = 14f; setTextColor(Palette.ON); typeface = Palette.medium
|
||||
setSingleLine(); ellipsize = TextUtils.TruncateAt.END
|
||||
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = px(10) })
|
||||
addView(TextView(activity).apply {
|
||||
text = "Connections"; textSize = 14f; setTextColor(Palette.VIOLET_SOFT); typeface = Palette.medium
|
||||
gravity = Gravity.CENTER; minHeight = px(48); setPadding(px(12), 0, px(12), 0)
|
||||
isClickable = true; isFocusable = true
|
||||
background = RippleDrawable(ColorStateList.valueOf(Palette.alpha(Palette.VIOLET, 60)), null, null)
|
||||
setOnClickListener { onConnections() }
|
||||
})
|
||||
}
|
||||
return LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL; setBackgroundColor(Palette.SPACE)
|
||||
addView(bar, LinearLayout.LayoutParams(-1, -2))
|
||||
addView(View(activity).apply { setBackgroundColor(Palette.LINE) }, LinearLayout.LayoutParams(-1, px(1)))
|
||||
setOnApplyWindowInsetsListener { v, insets ->
|
||||
v.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, 0); insets
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
/** Preserve connection work across a trip to Wi-Fi settings or another app. */
|
||||
class ConnectionRecovery(private val search: (Boolean) -> Unit, private val connect: () -> Unit,
|
||||
private val stopSearch: () -> Unit) {
|
||||
private var pending: (() -> Unit)? = null
|
||||
|
||||
fun stopped(searchAutomatic: Boolean?, disconnected: Boolean) {
|
||||
pending = when {
|
||||
searchAutomatic != null -> { { search(searchAutomatic) } }
|
||||
disconnected -> connect
|
||||
else -> null
|
||||
}
|
||||
stopSearch()
|
||||
}
|
||||
|
||||
fun resumed() {
|
||||
val action = pending
|
||||
pending = null
|
||||
action?.invoke()
|
||||
}
|
||||
}
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Dialog
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.graphics.drawable.RippleDrawable
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.Window
|
||||
import android.widget.*
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** How the app reaches comma, as stored in the "transport" preference. */
|
||||
enum class Transport(val key: String, val title: String, val icon: Int, val summary: String) {
|
||||
AUTO("auto", "Automatic", R.drawable.ic_route_auto, "Always checks Galaxy Wi-Fi and your home network before Bluetooth."),
|
||||
WIFI("wifi", "Wi-Fi & LAN", R.drawable.ic_route_wifi, "Galaxy Wi-Fi or your home network. Never Bluetooth."),
|
||||
BLUETOOTH("bluetooth", "Bluetooth", R.drawable.ic_route_bluetooth, "Bluetooth only, for when there's no Wi-Fi in reach.");
|
||||
companion object { fun of(key: String?) = entries.firstOrNull { it.key == key } ?: AUTO }
|
||||
}
|
||||
|
||||
/** Galaxy-styled bottom sheet with every connection choice, replacing the stock list dialog. */
|
||||
class ConnectionSheet(private val activity: Activity, current: Transport) {
|
||||
private val dp = activity.resources.displayMetrics.density
|
||||
private fun px(value: Number) = (value.toFloat() * dp).roundToInt()
|
||||
private val dialog = Dialog(activity)
|
||||
private val content = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(px(20), px(22), px(20), px(20)) }
|
||||
private val tiles = mutableMapOf<Transport, LinearLayout>()
|
||||
private val summary = text(13f, Palette.MUTED)
|
||||
private var selected = current
|
||||
|
||||
init {
|
||||
content.addView(text(22f, Palette.ON, Palette.condensed).apply { text = "Connections" })
|
||||
content.addView(LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
Transport.entries.forEachIndexed { index, transport ->
|
||||
val tile = tile(transport); tiles[transport] = tile
|
||||
addView(tile, LinearLayout.LayoutParams(0, px(84), 1f).apply { if (index > 0) marginStart = px(8) })
|
||||
}
|
||||
}, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(16) })
|
||||
content.addView(summary, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(10) })
|
||||
paint()
|
||||
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
|
||||
dialog.setContentView(ScrollView(activity).apply {
|
||||
addView(content)
|
||||
background = GradientDrawable().apply {
|
||||
val r = px(28).toFloat(); cornerRadii = floatArrayOf(r, r, r, r, 0f, 0f, 0f, 0f)
|
||||
setColor(Palette.SURFACE); setStroke(px(1), Palette.LINE)
|
||||
}
|
||||
})
|
||||
dialog.window?.apply {
|
||||
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
|
||||
setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
setGravity(Gravity.BOTTOM)
|
||||
setWindowAnimations(android.R.style.Animation_InputMethod)
|
||||
}
|
||||
}
|
||||
|
||||
/** Called with the new mode after the selection has had a moment on screen. */
|
||||
fun onTransport(choose: (Transport) -> Unit) = apply {
|
||||
tiles.forEach { (transport, tile) ->
|
||||
tile.setOnClickListener {
|
||||
selected = transport; paint()
|
||||
tile.postDelayed({ dismiss(); choose(transport) }, 180)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun group(title: String, build: Group.() -> Unit) = apply {
|
||||
content.addView(text(14f, Palette.VIOLET_SOFT, Palette.medium).apply { text = title },
|
||||
LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(24); marginStart = px(4) })
|
||||
val list = LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL; clipToOutline = true
|
||||
background = GradientDrawable().apply { cornerRadius = px(18).toFloat(); setColor(Palette.SPACE); setStroke(px(1), Palette.LINE) }
|
||||
}
|
||||
Group(list).build()
|
||||
content.addView(list, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(8) })
|
||||
}
|
||||
|
||||
inner class Group(private val list: LinearLayout) {
|
||||
fun action(title: String, detail: String? = null, danger: Boolean = false, run: () -> Unit) {
|
||||
if (list.childCount > 0) list.addView(View(activity).apply { setBackgroundColor(Palette.LINE) },
|
||||
LinearLayout.LayoutParams(-1, px(1)).apply { marginStart = px(16) })
|
||||
list.addView(LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_VERTICAL
|
||||
minimumHeight = px(56); setPadding(px(16), px(10), px(16), px(10))
|
||||
isClickable = true; isFocusable = true
|
||||
background = RippleDrawable(ColorStateList.valueOf(Palette.alpha(if (danger) Palette.ERROR else Palette.VIOLET, 60)), null, GradientDrawable().apply { setColor(Color.WHITE) })
|
||||
addView(text(16f, if (danger) Palette.ERROR else Palette.ON, Palette.medium).apply { text = title })
|
||||
if (detail != null) addView(text(13f, Palette.MUTED).apply { text = detail }, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(2) })
|
||||
contentDescription = if (detail == null) title else "$title. $detail"
|
||||
setOnClickListener { dismiss(); run() }
|
||||
}, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
}
|
||||
|
||||
fun show() { if (!activity.isFinishing && !activity.isDestroyed) dialog.show() }
|
||||
private fun dismiss() { if (dialog.isShowing) dialog.dismiss() }
|
||||
|
||||
private fun tile(transport: Transport) = LinearLayout(activity).apply {
|
||||
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER
|
||||
isClickable = true; isFocusable = true
|
||||
addView(ImageView(activity).apply { setImageResource(transport.icon) }, LinearLayout.LayoutParams(px(24), px(24)))
|
||||
addView(text(14f, Palette.ON, Palette.medium).apply { text = transport.title; gravity = Gravity.CENTER; maxLines = 1 },
|
||||
LinearLayout.LayoutParams(-2, -2).apply { topMargin = px(8) })
|
||||
}
|
||||
|
||||
private fun paint() {
|
||||
tiles.forEach { (transport, tile) ->
|
||||
val on = transport == selected
|
||||
val color = if (on) Palette.VIOLET_SOFT else Palette.MUTED
|
||||
(tile.getChildAt(0) as ImageView).imageTintList = ColorStateList.valueOf(color)
|
||||
(tile.getChildAt(1) as TextView).setTextColor(if (on) Palette.ON else Palette.MUTED)
|
||||
tile.isSelected = on
|
||||
tile.contentDescription = if (on) "${transport.title}, selected" else transport.title
|
||||
tile.background = RippleDrawable(ColorStateList.valueOf(Palette.alpha(Palette.VIOLET, 60)), GradientDrawable().apply {
|
||||
cornerRadius = px(18).toFloat()
|
||||
setColor(if (on) Palette.alpha(Palette.VIOLET, 40) else Palette.SPACE)
|
||||
setStroke(px(if (on) 1.5f else 1f), if (on) Palette.VIOLET else Palette.LINE)
|
||||
}, null)
|
||||
}
|
||||
summary.text = selected.summary
|
||||
}
|
||||
|
||||
private fun text(size: Float, color: Int, face: android.graphics.Typeface? = null) = TextView(activity).apply {
|
||||
textSize = size; setTextColor(color); face?.let { typeface = it }
|
||||
}
|
||||
}
|
||||
-252
@@ -1,252 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Network
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.ExecutionException
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
class GalaxyUpdateException(message: String) : Exception(message)
|
||||
|
||||
data class GalaxyAssetFile(val path: String, val sha256: String, val size: Int)
|
||||
|
||||
data class GalaxyAssetManifest(val files: List<GalaxyAssetFile>) {
|
||||
fun validate() {
|
||||
if (files.size !in 1..512 || files.map { it.path }.toSet().size != files.size) throw GalaxyUpdateException("Galaxy update needs a compatible app version.")
|
||||
var total = 0L
|
||||
for (file in files) {
|
||||
val parts = file.path.split('/')
|
||||
if (parts.any { it.isEmpty() || it == "." || it == ".." } ||
|
||||
!file.path.all { it in '0'..'9' || it in 'A'..'Z' || it in 'a'..'z' || it in "-./_" } ||
|
||||
!(file.path in ROOT_FILES || ROOT_DIRS.any { file.path.startsWith(it) }) ||
|
||||
file.size !in 0..MAX_FILE || !isHash(file.sha256)) throw GalaxyUpdateException("Invalid Galaxy update file.")
|
||||
total += file.size
|
||||
}
|
||||
val paths = files.map { it.path }.toSet()
|
||||
if (total > MAX_TOTAL || !paths.containsAll(REQUIRED) || paths.any { it == "data/runtime.json" || it.endsWith(".sample.json") }) {
|
||||
throw GalaxyUpdateException("Galaxy update is incomplete or too large.")
|
||||
}
|
||||
}
|
||||
|
||||
fun encode() = "galaxy-assets 1\n" + files.sortedBy { it.path }.joinToString("") { "${it.sha256} ${it.size} ${it.path}\n" }
|
||||
|
||||
companion object {
|
||||
const val MAX_FILE = 4 * 1024 * 1024
|
||||
const val MAX_TOTAL = 32L * 1024 * 1024
|
||||
private val ROOT_FILES = setOf("index.html", "manifest.webmanifest", "sentry-push-worker.js")
|
||||
private val ROOT_DIRS = listOf("assets/", "css/", "js/", "vendor/", "data/")
|
||||
private val REQUIRED = setOf("index.html", "js/boot.js", "js/app.js", "data/catalog.json")
|
||||
|
||||
fun isHash(value: String) = value.length == 64 && value.all { it in '0'..'9' || it in 'a'..'f' }
|
||||
fun sha256(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
|
||||
|
||||
fun decode(text: String): GalaxyAssetManifest? {
|
||||
val lines = text.split('\n').dropLastWhile { it.isEmpty() }
|
||||
if (lines.firstOrNull() != "galaxy-assets 1") return null
|
||||
return GalaxyAssetManifest(lines.drop(1).map { line ->
|
||||
val parts = line.split(' ')
|
||||
if (parts.size != 3) return null
|
||||
GalaxyAssetFile(parts[2], parts[0], parts[1].toIntOrNull() ?: return null)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Comma has no page inventory endpoint: an older build that cannot share its Galaxy screens. */
|
||||
class GalaxyTooOldException : Exception()
|
||||
|
||||
/** What comma serves: its page inventory and the pages themselves. Android implements it over LAN HTTP, tests in memory. */
|
||||
interface GalaxySource {
|
||||
class Listing(val commit: String?, val files: List<GalaxyAssetFile>)
|
||||
fun manifest(): Listing
|
||||
fun file(path: String, limit: Int): ByteArray
|
||||
}
|
||||
|
||||
interface GalaxyPrefs {
|
||||
fun get(key: String): String?
|
||||
fun set(key: String, value: String)
|
||||
}
|
||||
|
||||
/** Keeps the Bluetooth copy of Galaxy matched to the pages comma serves, downloaded over Wi-Fi/LAN. */
|
||||
class GalaxyAssetStore(private val cacheRoot: File, private val prefs: GalaxyPrefs) {
|
||||
@Volatile var status = NOT_DOWNLOADED; private set
|
||||
@Volatile var readyRoot: File? = null; private set
|
||||
@Volatile var inUseRoot: File? = null
|
||||
|
||||
init {
|
||||
// Validate saved assets before trusting a previous completed update.
|
||||
prefs.get(MANIFEST_KEY)?.takeIf { GalaxyAssetManifest.isHash(it) }?.let { hash ->
|
||||
val root = File(cacheRoot, hash)
|
||||
if (verify(root)) { readyRoot = root; status = "Using Galaxy screens saved from comma." }
|
||||
}
|
||||
}
|
||||
|
||||
/** True when comma now runs a different build than the one these screens came from. */
|
||||
fun olderThan(commaCommit: String?): Boolean {
|
||||
val saved = prefs.get(COMMIT_KEY)?.takeIf { it.isNotEmpty() }
|
||||
return readyRoot != null && saved != null && !commaCommit.isNullOrEmpty() && saved != commaCommit
|
||||
}
|
||||
|
||||
/** Compares comma's inventory with the saved copy and downloads only what changed. Never skips on an unchanged commit. */
|
||||
fun check(source: GalaxySource) {
|
||||
status = "Checking comma for Galaxy updates…"
|
||||
var stage: File? = null
|
||||
val pool = Executors.newFixedThreadPool(4)
|
||||
try {
|
||||
val listing = source.manifest()
|
||||
val manifest = GalaxyAssetManifest(listing.files.sortedBy { it.path }).apply { validate() }
|
||||
val data = manifest.encode().toByteArray()
|
||||
val hash = GalaxyAssetManifest.sha256(data)
|
||||
val saved = readyRoot
|
||||
if (saved?.name == hash) { prefs.set(COMMIT_KEY, listing.commit ?: ""); status = "Galaxy matches comma."; return }
|
||||
cacheRoot.mkdirs()
|
||||
val staging = File(cacheRoot, "staging-" + UUID.randomUUID()).also { stage = it; it.mkdirs() }
|
||||
var done = 0
|
||||
for (batch in manifest.files.chunked(4)) {
|
||||
if (Thread.currentThread().isInterrupted) throw InterruptedException()
|
||||
val results = pool.invokeAll(batch.map { entry -> Callable {
|
||||
fun matches(bytes: ByteArray?) = bytes != null && bytes.size == entry.size && GalaxyAssetManifest.sha256(bytes) == entry.sha256
|
||||
val local = saved?.let { File(it, entry.path).takeIf(File::isFile)?.readBytes() }?.takeIf(::matches)
|
||||
entry.path to (local ?: source.file(entry.path, maxOf(entry.size, 1)).also {
|
||||
if (!matches(it)) throw GalaxyUpdateException("Galaxy update verification failed.")
|
||||
})
|
||||
} })
|
||||
for (result in results) {
|
||||
val (path, bytes) = try { result.get() } catch (e: ExecutionException) { throw e.cause ?: e }
|
||||
File(staging, path).apply { parentFile?.mkdirs(); writeBytes(bytes) }
|
||||
}
|
||||
done += batch.size
|
||||
status = "Preparing Galaxy update ($done/${manifest.files.size})…"
|
||||
}
|
||||
File(staging, MANIFEST_FILE).writeBytes(data)
|
||||
val destination = File(cacheRoot, hash)
|
||||
if (destination.exists()) destination.deleteRecursively()
|
||||
if (!staging.renameTo(destination)) throw GalaxyUpdateException("Galaxy update could not be saved.")
|
||||
stage = null
|
||||
readyRoot = destination
|
||||
prefs.set(MANIFEST_KEY, hash)
|
||||
prefs.set(COMMIT_KEY, listing.commit ?: "")
|
||||
// Keep one previous version while an open WebView is still using it.
|
||||
val keep = setOfNotNull(destination.canonicalPath, saved?.canonicalPath, inUseRoot?.canonicalPath)
|
||||
cacheRoot.listFiles()?.filter { it.canonicalPath !in keep }?.forEach { it.deleteRecursively() }
|
||||
status = "Galaxy update ready. It applies when you next open Galaxy over Bluetooth."
|
||||
} catch (error: Exception) {
|
||||
stage?.deleteRecursively()
|
||||
val using = if (readyRoot == null) "No Galaxy screens are saved yet." else "Using your saved Galaxy screens."
|
||||
status = when (error) {
|
||||
is GalaxyTooOldException -> "Comma’s software is too old to share Galaxy screens; update comma. $using"
|
||||
is GalaxyUpdateException -> "${error.message} $using"
|
||||
is InterruptedException -> "Galaxy update cancelled. $using"
|
||||
is java.io.IOException -> "Couldn’t reach comma to check Galaxy updates. $using"
|
||||
else -> "Galaxy update could not be read or saved. $using"
|
||||
}
|
||||
} finally { pool.shutdownNow() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NOT_DOWNLOADED = "Galaxy screens aren’t downloaded yet. Connect to comma over Wi-Fi once."
|
||||
const val MANIFEST_FILE = "manifest.txt"
|
||||
private const val MANIFEST_KEY = "galaxy.assets.manifest"
|
||||
private const val COMMIT_KEY = "galaxy.comma.commit"
|
||||
|
||||
fun verify(root: File): Boolean {
|
||||
val data = File(root, MANIFEST_FILE).takeIf(File::isFile)?.readBytes() ?: return false
|
||||
if (GalaxyAssetManifest.sha256(data) != root.name) return false
|
||||
val manifest = GalaxyAssetManifest.decode(String(data)) ?: return false
|
||||
if (runCatching { manifest.validate() }.isFailure) return false
|
||||
return manifest.files.all { file ->
|
||||
val bytes = File(root, file.path).takeIf(File::isFile)?.readBytes() ?: return@all false
|
||||
bytes.size == file.size && GalaxyAssetManifest.sha256(bytes) == file.sha256
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Android wiring: one store per process; downloads run over the Wi-Fi/LAN network that reaches comma. */
|
||||
object GalaxyUpdates {
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val checking = AtomicBoolean()
|
||||
|
||||
@Volatile private var store: GalaxyAssetStore? = null
|
||||
|
||||
fun store(context: Context): GalaxyAssetStore = store ?: synchronized(this) {
|
||||
store ?: run {
|
||||
val app = context.applicationContext
|
||||
val prefs = app.getSharedPreferences("companion", Context.MODE_PRIVATE)
|
||||
GalaxyAssetStore(File(app.filesDir, "galaxy-updates"), object : GalaxyPrefs {
|
||||
override fun get(key: String) = prefs.getString(key, null)
|
||||
override fun set(key: String, value: String) { prefs.edit().putString(key, value).apply() }
|
||||
}).also { store = it }
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether comma's build, from a Bluetooth /api/software/status read, differs from the saved screens. */
|
||||
fun olderThanComma(context: Context, status: JSONObject) =
|
||||
store(context).olderThan(status.optJSONObject("installed")?.optString("commit")?.ifEmpty { null })
|
||||
|
||||
/** Download comma's screens from [network]/[origin] in the background. */
|
||||
fun refreshAsync(context: Context, network: Network, origin: String, done: ((String) -> Unit)? = null) {
|
||||
val app = context.applicationContext
|
||||
if (!checking.compareAndSet(false, true)) { done?.invoke(store(app).status); return }
|
||||
executor.execute {
|
||||
try {
|
||||
val store = store(app)
|
||||
store.check(CommaSource(network, origin))
|
||||
done?.invoke(store.status)
|
||||
} finally { checking.set(false) }
|
||||
}
|
||||
}
|
||||
|
||||
/** For the menu: refresh when the phone can reach comma over Wi-Fi/LAN, otherwise explain. */
|
||||
fun checkAsync(context: Context, done: (String) -> Unit) {
|
||||
val reach = Networks.commaLan(context)
|
||||
if (reach == null) done("Join comma’s Wi-Fi or home network to refresh Galaxy screens.")
|
||||
else refreshAsync(context, reach.first, reach.second, done)
|
||||
}
|
||||
|
||||
private class CommaSource(private val network: Network, private val origin: String) : GalaxySource {
|
||||
override fun manifest(): GalaxySource.Listing {
|
||||
val json = JSONObject(String(get("/api/companion/web-manifest", 1024 * 1024, 5000, inventory = true)))
|
||||
if (json.optInt("schema") != 1) throw GalaxyTooOldException()
|
||||
val array = json.getJSONArray("files")
|
||||
val files = (0 until array.length()).map { array.getJSONObject(it) }
|
||||
.map { GalaxyAssetFile(it.getString("path"), it.getString("sha256"), it.getInt("size")) }
|
||||
return GalaxySource.Listing(json.optString("commit").ifEmpty { null }, files)
|
||||
}
|
||||
|
||||
override fun file(path: String, limit: Int) = get("/$path", limit, 15000)
|
||||
|
||||
private fun get(path: String, limit: Int, timeout: Int, inventory: Boolean = false): ByteArray {
|
||||
val connection = network.openConnection(URL(origin + path)) as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = timeout; connection.readTimeout = timeout
|
||||
connection.instanceFollowRedirects = false
|
||||
// Hashes cover the file bytes as stored, so ask for them unencoded.
|
||||
connection.setRequestProperty("Accept-Encoding", "identity")
|
||||
// Older comma builds answer 401 (no session) or 404 for the inventory path.
|
||||
if (inventory && connection.responseCode in setOf(401, 404)) throw GalaxyTooOldException()
|
||||
if (connection.responseCode != 200) throw GalaxyUpdateException("Comma returned HTTP ${connection.responseCode} for Galaxy screens.")
|
||||
return connection.inputStream.use { read(it, limit) }
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
private fun read(input: InputStream, limit: Int): ByteArray {
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) return output.toByteArray()
|
||||
if (output.size() + count > limit) throw GalaxyUpdateException("Galaxy update file was larger than expected.")
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.net.Network
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/** A short application-level acknowledgement before committing the UI to Wi-Fi. */
|
||||
object GalaxyProbe {
|
||||
const val TIMEOUT_MS = 900
|
||||
const val AUTOMATIC_DISCOVERY_MS = 2500L
|
||||
private const val MAX_RESPONSE_BYTES = 1024
|
||||
|
||||
fun accepts(status: Int, contentType: String?, authenticated: Boolean, localAccess: Boolean): Boolean =
|
||||
status == 200 && contentType?.substringBefore(';')?.trim()?.equals("application/json", ignoreCase = true) == true &&
|
||||
authenticated && localAccess
|
||||
|
||||
fun reachable(network: Network, origin: String, cookie: String?, opened: (HttpURLConnection) -> Unit): Boolean {
|
||||
require(Networks.localOrigin(origin) == origin)
|
||||
val connection = network.openConnection(URL("$origin/api/auth/session")) as HttpURLConnection
|
||||
opened(connection)
|
||||
return try {
|
||||
connection.connectTimeout = TIMEOUT_MS
|
||||
connection.readTimeout = TIMEOUT_MS
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
connection.setRequestProperty("Connection", "close")
|
||||
if (!cookie.isNullOrBlank()) connection.setRequestProperty("Cookie", cookie)
|
||||
val status = connection.responseCode
|
||||
val input = if (status == 200) connection.inputStream else connection.errorStream ?: return false
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
input.use {
|
||||
val buffer = ByteArray(256)
|
||||
while (true) {
|
||||
val count = it.read(buffer)
|
||||
if (count < 0) break
|
||||
if (output.size() + count > MAX_RESPONSE_BYTES) return false
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
val value = JSONObject(output.toString(Charsets.UTF_8.name()))
|
||||
accepts(status, connection.contentType, value.optBoolean("authenticated"), value.optBoolean("localAccess"))
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Network
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import java.net.Inet4Address
|
||||
import java.util.concurrent.Executor
|
||||
|
||||
/** One bounded foreground search. All callbacks and state changes run on the main thread. */
|
||||
class LanDiscovery(context: Context, private val network: Network, private val timeoutMs: Long = 12000L,
|
||||
private val complete: (List<String>, String?) -> Unit) {
|
||||
companion object {
|
||||
const val SERVICE = "_sp-galaxy._tcp."
|
||||
private const val SUCCESS_SETTLE_MS = 500L
|
||||
}
|
||||
private val nsd = context.getSystemService(NsdManager::class.java)
|
||||
private val wifi = context.applicationContext.getSystemService(WifiManager::class.java)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val executor = Executor { handler.post(it) }
|
||||
private val pending = ArrayDeque<NsdServiceInfo>()
|
||||
private val seen = mutableSetOf<String>()
|
||||
private val hosts = linkedSetOf<String>()
|
||||
private var active = false
|
||||
private var discoveryRequested = false
|
||||
private var resolving: NsdManager.ResolveListener? = null
|
||||
private var lock: WifiManager.MulticastLock? = null
|
||||
private var lastError: String? = null
|
||||
private val timeout = Runnable { finish(lastError) }
|
||||
private val settle = Runnable { if (hosts.isNotEmpty() && resolving == null && pending.isEmpty()) finish(null) }
|
||||
|
||||
private val listener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(type: String) {}
|
||||
override fun onDiscoveryStopped(type: String) {}
|
||||
override fun onStartDiscoveryFailed(type: String, code: Int) { handler.post {
|
||||
if (active) { discoveryRequested = false; finish("LAN discovery could not start (Android error $code).") }
|
||||
} }
|
||||
override fun onStopDiscoveryFailed(type: String, code: Int) { Log.w("GalaxyLAN", "Stop discovery failed: $code") }
|
||||
override fun onServiceLost(info: NsdServiceInfo) {}
|
||||
override fun onServiceFound(info: NsdServiceInfo) { handler.post {
|
||||
if (active && seen.add(info.serviceName)) {
|
||||
handler.removeCallbacks(settle)
|
||||
pending.addLast(info)
|
||||
resolveNext()
|
||||
}
|
||||
} }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
check(!active)
|
||||
active = true
|
||||
try {
|
||||
// Older Android/OEM Wi-Fi stacks filter multicast without this lock.
|
||||
lock = wifi.createMulticastLock("GalaxyLAN").apply { setReferenceCounted(false); acquire() }
|
||||
if (Build.VERSION.SDK_INT >= 33) nsd.discoverServices(SERVICE, NsdManager.PROTOCOL_DNS_SD, network, executor, listener)
|
||||
else nsd.discoverServices(SERVICE, NsdManager.PROTOCOL_DNS_SD, listener)
|
||||
discoveryRequested = true
|
||||
handler.postDelayed(timeout, timeoutMs)
|
||||
} catch (error: RuntimeException) {
|
||||
Log.w("GalaxyLAN", "Discovery failed", error)
|
||||
finish("LAN discovery could not start. Check Wi-Fi and local network access.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveNext() {
|
||||
if (!active || resolving != null || pending.isEmpty()) return
|
||||
val info = pending.removeFirst()
|
||||
val resolver = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(service: NsdServiceInfo, code: Int) { handler.post {
|
||||
if (active && resolving === this) {
|
||||
lastError = "Comma was advertised, but its LAN address could not be resolved (Android error $code)."
|
||||
Log.w("GalaxyLAN", "Resolve failed: $code")
|
||||
resolving = null; resolveNext()
|
||||
}
|
||||
} }
|
||||
override fun onServiceResolved(service: NsdServiceInfo) { handler.post {
|
||||
if (active && resolving === this) {
|
||||
val addresses = if (Build.VERSION.SDK_INT >= 34) service.hostAddresses else listOfNotNull(service.host)
|
||||
addresses.filterIsInstance<Inet4Address>().forEach { address ->
|
||||
Networks.localOrigin("http://${address.hostAddress}:${service.port}")?.let { hosts.add(it) }
|
||||
}
|
||||
resolving = null; resolveNext(); settleIfReady()
|
||||
}
|
||||
} }
|
||||
}
|
||||
resolving = resolver
|
||||
try { nsd.resolveService(info, resolver) }
|
||||
catch (error: RuntimeException) {
|
||||
Log.w("GalaxyLAN", "Resolve failed", error)
|
||||
lastError = "Comma was advertised, but Android could not resolve its LAN address."
|
||||
resolving = null; resolveNext(); settleIfReady()
|
||||
}
|
||||
}
|
||||
|
||||
/** Allow a brief window for another advertised comma, without imposing the full discovery timeout. */
|
||||
private fun settleIfReady() {
|
||||
if (hosts.isEmpty() || resolving != null || pending.isNotEmpty()) return
|
||||
handler.removeCallbacks(settle)
|
||||
handler.postDelayed(settle, SUCCESS_SETTLE_MS)
|
||||
}
|
||||
|
||||
private fun finish(error: String?) {
|
||||
if (!active) return
|
||||
val result = hosts.toList()
|
||||
close()
|
||||
complete(result, error)
|
||||
}
|
||||
|
||||
fun close() {
|
||||
active = false
|
||||
handler.removeCallbacks(timeout)
|
||||
handler.removeCallbacks(settle)
|
||||
if (discoveryRequested) runCatching { nsd.stopServiceDiscovery(listener) }
|
||||
discoveryRequested = false
|
||||
if (Build.VERSION.SDK_INT >= 34) resolving?.let { runCatching { nsd.stopServiceResolution(it) } }
|
||||
resolving = null; pending.clear()
|
||||
lock?.let { if (it.isHeld) it.release() }; lock = null
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.net.Network
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/** Whether comma can take a phone's Bluetooth pairing right now, from its /api/companion/bluetooth-ready. */
|
||||
data class CommaReadiness(val ready: Boolean, val code: String, val message: String)
|
||||
|
||||
/** What opening comma's phone pairing window needs from the network; tests supply it in memory. */
|
||||
interface LanPairingApi {
|
||||
/** comma's answer to "are you ready to pair?", or null from an older comma that cannot say. */
|
||||
fun readiness(cookie: String): CommaReadiness? = null
|
||||
/** Session cookie when comma accepts this phone's local Galaxy session, otherwise null. */
|
||||
fun session(): String?
|
||||
/** POST [body] to [path] with that session; returns the HTTP status and response body. */
|
||||
fun post(path: String, body: String, cookie: String): Pair<Int, String>
|
||||
}
|
||||
|
||||
/**
|
||||
* When the phone already reaches comma over Wi-Fi/LAN it opens comma's two-minute pairing window itself, the same call
|
||||
* as Pair phone on Galaxy's Bluetooth page, so nobody has to touch comma before the Bluetooth key claim.
|
||||
*/
|
||||
object LanPairing {
|
||||
const val READY_PATH = "/api/companion/bluetooth-ready"
|
||||
private val WAITABLE = setOf("starting", "bridge_starting")
|
||||
const val WINDOW_PATH = "/api/bluetooth/action"
|
||||
const val WINDOW_BODY = "{\"operation\":\"accept_pair\"}"
|
||||
|
||||
/**
|
||||
* Null when comma is ready to pair (or is too old to say), otherwise why not. Short-lived states, such as comma
|
||||
* just booting or its Bluetooth bridge starting, are waited out for up to [maxWaitMs]; the rest need someone at comma.
|
||||
*/
|
||||
fun waitUntilReady(api: LanPairingApi, maxWaitMs: Long = 45000, stepMs: Long = 3000,
|
||||
onWait: (String) -> Unit = {}, pause: (Long) -> Unit = { Thread.sleep(it) }): CommaReadiness? {
|
||||
val cookie = runCatching { api.session() }.getOrNull() ?: return null
|
||||
var waited = 0L
|
||||
while (true) {
|
||||
val answer = runCatching { api.readiness(cookie) }.getOrNull() ?: return null
|
||||
if (answer.ready) return null
|
||||
if (answer.code !in WAITABLE || waited >= maxWaitMs) return answer
|
||||
onWait(answer.message)
|
||||
pause(stepMs); waited += stepMs
|
||||
}
|
||||
}
|
||||
|
||||
fun waitUntilReady(network: Network, origin: String, onWait: (String) -> Unit = {}): CommaReadiness? =
|
||||
waitUntilReady(realApi(network, origin), onWait = onWait)
|
||||
|
||||
/**
|
||||
* Null when the window opened, otherwise why not, in words fit for the pairing screen. comma answers 409 busy while
|
||||
* Android Auto or Bluetooth is still settling (for example just after a reboot), so that one answer is retried a few times.
|
||||
*/
|
||||
fun openWindow(api: LanPairingApi, attempts: Int = 4, pause: (Long) -> Unit = { Thread.sleep(it) }): String? {
|
||||
var reason: String? = null
|
||||
for (attempt in 1..attempts) {
|
||||
val (why, busy) = once(api)
|
||||
reason = why
|
||||
if (why == null || !busy || attempt == attempts) break
|
||||
pause(2500)
|
||||
}
|
||||
return reason
|
||||
}
|
||||
|
||||
private fun once(api: LanPairingApi): Pair<String?, Boolean> = try {
|
||||
val cookie = api.session()
|
||||
if (cookie == null) "comma gave this phone no local Galaxy session" to false
|
||||
else {
|
||||
val (status, body) = api.post(WINDOW_PATH, WINDOW_BODY, cookie)
|
||||
val code = Regex("\"code\"\\s*:\\s*\"([a-z_]+)\"").find(body)?.groupValues?.get(1)
|
||||
if (status == 200) null to false
|
||||
else "comma answered HTTP $status${code?.let { " ($it)" }.orEmpty()}" to (status == 409 && code == "busy")
|
||||
}
|
||||
} catch (e: Exception) { (e.message ?: e.javaClass.simpleName) to false }
|
||||
|
||||
fun openWindow(network: Network, origin: String): String? = openWindow(realApi(network, origin))
|
||||
|
||||
private fun realApi(network: Network, origin: String) = object : LanPairingApi {
|
||||
override fun readiness(cookie: String): CommaReadiness? {
|
||||
val connection = open(network, origin, READY_PATH, cookie)
|
||||
try {
|
||||
if (connection.responseCode != 200) return null
|
||||
val json = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
|
||||
if (json.optInt("schema") != 1 || !json.has("ready")) return null
|
||||
return CommaReadiness(json.getBoolean("ready"), json.optString("code"), json.optString("message"))
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
override fun session(): String? {
|
||||
val connection = open(network, origin, "/api/auth/session", "")
|
||||
try {
|
||||
if (connection.responseCode != 200) return null
|
||||
val json = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
|
||||
if (!json.optBoolean("authenticated") || !json.optBoolean("localAccess")) return null
|
||||
return connection.getHeaderField("Set-Cookie")?.substringBefore(';')?.ifEmpty { null }
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
|
||||
override fun post(path: String, body: String, cookie: String): Pair<Int, String> {
|
||||
val connection = open(network, origin, path, cookie)
|
||||
try {
|
||||
connection.readTimeout = 35000
|
||||
connection.requestMethod = "POST"; connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.outputStream.use { it.write(body.toByteArray()) }
|
||||
val status = connection.responseCode
|
||||
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
|
||||
return status to (stream?.bufferedReader()?.use { it.readText() } ?: "")
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun open(network: Network, origin: String, path: String, cookie: String) =
|
||||
(network.openConnection(URL(origin + path)) as HttpURLConnection).apply {
|
||||
connectTimeout = 3000; readTimeout = 3000; instanceFollowRedirects = false
|
||||
setRequestProperty("Origin", origin)
|
||||
if (cookie.isNotEmpty()) setRequestProperty("Cookie", cookie)
|
||||
}
|
||||
}
|
||||
-937
@@ -1,937 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.pm.PackageManager
|
||||
import java.net.HttpURLConnection
|
||||
import java.util.Base64
|
||||
import java.util.concurrent.*
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.*
|
||||
import android.widget.*
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.File
|
||||
import java.net.Inet4Address
|
||||
|
||||
class MainActivity : Activity() {
|
||||
@Volatile private var web: WebView? = null
|
||||
private var ble: BleTransport? = null
|
||||
private val connectionGeneration = AtomicInteger()
|
||||
@Volatile private var bluetoothMode = false
|
||||
private var bluetoothAttemptAutomatic = false
|
||||
private val pairing by lazy { PairingStore(this) }
|
||||
private val jobs = ConcurrentHashMap<String, FutureTask<Unit>>()
|
||||
private val probes = ConcurrentHashMap<Int, HttpURLConnection>()
|
||||
private val worker = ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, ArrayBlockingQueue(16))
|
||||
private val cachedOrigin = "https://galaxy-app.invalid"
|
||||
private var screen: ConnectScreen? = null
|
||||
private val recovery = ConnectionRecovery({ discoverLan(it) }, { connect() }, { stopDiscovery() })
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var pageWatchdog: Runnable? = null
|
||||
private var pendingInstallOrigin: String? = null
|
||||
private var resumed = false
|
||||
private val knownWifi = mutableSetOf<Network>()
|
||||
private val wifiWatcher = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
if (network in knownWifi || properties.linkAddresses.none { it.address is Inet4Address && it.address.isSiteLocalAddress }) return
|
||||
knownWifi.add(network)
|
||||
// Open Galaxy as soon as the phone joins a Wi-Fi network, without waiting for "Try again".
|
||||
handler.post {
|
||||
val mayPreemptBluetooth = bluetoothAttemptAutomatic && screen?.state(Route.BLUETOOTH) == RouteState.TRYING
|
||||
if (idle() || mayPreemptBluetooth) connect()
|
||||
}
|
||||
}
|
||||
override fun onLost(network: Network) { knownWifi.remove(network) }
|
||||
}
|
||||
|
||||
private var origin = Networks.ORIGIN
|
||||
private var share: String? = null
|
||||
private val prefs by lazy { getSharedPreferences("companion", MODE_PRIVATE) }
|
||||
override fun onCreate(state: Bundle?) {
|
||||
super.onCreate(state)
|
||||
share = intent.getStringExtra("share")?.take(8192)
|
||||
AppUpdates.initialize(this)
|
||||
AppUpdateCompletion.opened(this)
|
||||
val cm = Networks.manager(this)
|
||||
knownWifi.addAll(cm.allNetworks.filter { cm.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true })
|
||||
// Galaxy Wi-Fi may have no internet, so do not require that capability.
|
||||
runCatching { cm.registerNetworkCallback(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), wifiWatcher, handler) }
|
||||
val bondFilter = android.content.IntentFilter(android.bluetooth.BluetoothDevice.ACTION_BOND_STATE_CHANGED)
|
||||
if (Build.VERSION.SDK_INT >= 33) registerReceiver(bondWatcher, bondFilter, RECEIVER_EXPORTED) else registerReceiver(bondWatcher, bondFilter)
|
||||
checkMusicBond()
|
||||
if (!requestNotificationPermission(7)) connect(Networks.localOrigin(intent.getStringExtra(AppUpdates.ORIGIN_EXTRA) ?: ""))
|
||||
if (PhoneGpsService.enabled(prefs) && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
startForegroundService(Intent(this, PhoneGpsService::class.java))
|
||||
}
|
||||
}
|
||||
private fun idle() = resumed && !isFinishing && web == null && ble == null && discovery == null && lanPicker == null && screen?.busy() == false
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
AppUpdateCompletion.opened(this)
|
||||
share = intent.getStringExtra("share")?.take(8192)
|
||||
connect(Networks.localOrigin(intent.getStringExtra(AppUpdates.ORIGIN_EXTRA) ?: ""))
|
||||
}
|
||||
/** Invalidates every older async result before a new route is allowed to win. */
|
||||
private fun supersedeConnection(): Int {
|
||||
stopDiscovery()
|
||||
val generation = connectionGeneration.incrementAndGet()
|
||||
jobs.values.forEach { it.cancel(false) }; jobs.clear(); worker.purge()
|
||||
ble?.close(); ble = null
|
||||
bluetoothMode = false
|
||||
bluetoothAttemptAutomatic = false
|
||||
clearWatchdog()
|
||||
val previous = web; web = null
|
||||
previous?.removeJavascriptInterface("StarPilotApp"); previous?.stopLoading(); previous?.destroy()
|
||||
Networks.manager(this).bindProcessToNetwork(null)
|
||||
return generation
|
||||
}
|
||||
private fun connect(host: String? = null) {
|
||||
val generation = supersedeConnection()
|
||||
val mode = prefs.getString("transport", "auto")
|
||||
if (host == null && mode == "bluetooth") { connectBluetooth(); return }
|
||||
val hotspot = Networks.wifi(this)
|
||||
val wifi = hotspot ?: Networks.wifi(this, false)
|
||||
if (wifi == null) {
|
||||
if (!bluetoothFallback()) disconnected()
|
||||
return
|
||||
}
|
||||
val saved = Networks.localOrigin(prefs.getString("host", "") ?: "")
|
||||
if (host == null) {
|
||||
val candidate = if (hotspot != null) Networks.ORIGIN else saved?.takeIf { it != Networks.ORIGIN }
|
||||
if (candidate != null) probeWifi(wifi.first, candidate, generation)
|
||||
else {
|
||||
disconnected()
|
||||
// Give LAN discovery a short, bounded head start before Automatic falls back to Bluetooth.
|
||||
discoverLan(automatic = true)
|
||||
}
|
||||
return
|
||||
}
|
||||
val localOrigin = Networks.localOrigin(host)
|
||||
if (localOrigin == null) { disconnected(); return }
|
||||
origin = localOrigin
|
||||
Networks.manager(this).bindProcessToNetwork(wifi.first)
|
||||
val route = if (origin == Networks.ORIGIN) Route.GALAXY_WIFI else Route.HOME_NETWORK
|
||||
connectScreen().apply {
|
||||
refreshRoutes(this)
|
||||
headline("Opening Galaxy")
|
||||
if (route == Route.GALAXY_WIFI) { route(route, RouteState.TRYING, "Opening…"); detail("Joined the comma's Wi-Fi.") }
|
||||
else { route(route, RouteState.TRYING, "Opening ${address(origin)}…"); detail("Reaching comma on this Wi-Fi network.") }
|
||||
}
|
||||
val view = WebView(this)
|
||||
web = view
|
||||
view.setBackgroundColor(Color.rgb(7, 7, 18))
|
||||
view.settings.javaScriptEnabled = true
|
||||
view.settings.domStorageEnabled = true
|
||||
view.settings.allowFileAccess = false
|
||||
view.settings.allowContentAccess = false
|
||||
view.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
CookieManager.getInstance().setAcceptThirdPartyCookies(view, false)
|
||||
view.addJavascriptInterface(Bridge(), "StarPilotApp")
|
||||
view.webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean {
|
||||
// No external document (including frames) ever receives the bridge.
|
||||
return Networks.localOrigin(request.url.toString()) != origin
|
||||
}
|
||||
override fun shouldInterceptRequest(v: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||
if (Networks.localOrigin(request.url.toString()) == origin) return null
|
||||
return WebResourceResponse("text/plain", "UTF-8", 403, "Local Galaxy only", emptyMap(), ByteArrayInputStream(byteArrayOf()))
|
||||
}
|
||||
override fun onReceivedError(v: WebView, request: WebResourceRequest, error: WebResourceError) {
|
||||
if (web === v && request.isForMainFrame) runOnUiThread { pageFailed(v) }
|
||||
}
|
||||
// Reveal as soon as Galaxy starts drawing, so a slow asset never trips the watchdog.
|
||||
override fun onPageCommitVisible(v: WebView, url: String) { if (web === v && Networks.localOrigin(url) == origin) revealWeb() }
|
||||
override fun onPageFinished(v: WebView, url: String) {
|
||||
if (web === v && Networks.localOrigin(url) == origin) {
|
||||
prefs.edit().putString("host", origin).apply(); share = null; revealWeb()
|
||||
AppUpdates.checkAsync(this@MainActivity)
|
||||
autoPairIfNeeded()
|
||||
}
|
||||
}
|
||||
}
|
||||
view.setDownloadListener { url, _, _, _, _ ->
|
||||
val uri = Uri.parse(url)
|
||||
if (Networks.localOrigin(url) == origin && uri.path in setOf("/app.apk", "/api/companion/app.apk")) {
|
||||
runOnUiThread { requestAppUpdate() }
|
||||
} else if (Networks.localOrigin(url) == origin) startActivity(Intent(Intent.ACTION_VIEW, uri))
|
||||
}
|
||||
showWeb(view, route, if (route == Route.GALAXY_WIFI) "Galaxy Wi-Fi" else "Home network, ${address(origin)}", waitForPage = true)
|
||||
// A comma that vanished mid-load can leave the page pending for a long time.
|
||||
val watchdogMs = if (route == Route.HOME_NETWORK && mode == "auto" && pairing.load() != null) 4000L else 10000L
|
||||
pageWatchdog = Runnable { if (web === view && screen != null) pageFailed(view) }.also { handler.postDelayed(it, watchdogMs) }
|
||||
view.loadUrl(if (share != null) "$origin/?share=${Uri.encode(share)}#/navigation" else "$origin/#/galaxy")
|
||||
if (prefs.getBoolean("enabled", false)) startForegroundService(Intent(this, UplinkService::class.java))
|
||||
}
|
||||
private fun probeWifi(network: Network, candidate: String, generation: Int, automatic: Boolean = true) {
|
||||
val route = if (candidate == Networks.ORIGIN) Route.GALAXY_WIFI else Route.HOME_NETWORK
|
||||
connectScreen().apply {
|
||||
refreshRoutes(this)
|
||||
headline("Checking Wi-Fi")
|
||||
route(route, RouteState.TRYING, "Checking…")
|
||||
detail(if (route == Route.GALAXY_WIFI) "Waiting for Galaxy to answer on comma Wi-Fi."
|
||||
else "Checking the last comma address before searching this network.")
|
||||
}
|
||||
val cookie = CookieManager.getInstance().getCookie(candidate)
|
||||
Thread({
|
||||
var connection: HttpURLConnection? = null
|
||||
val reachable = GalaxyProbe.reachable(network, candidate, cookie) {
|
||||
connection = it
|
||||
probes[generation] = it
|
||||
if (generation != connectionGeneration.get()) it.disconnect()
|
||||
}
|
||||
connection?.let { probes.remove(generation, it) }
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed || generation != connectionGeneration.get()) return@runOnUiThread
|
||||
if (reachable) connect(candidate)
|
||||
else if (route == Route.HOME_NETWORK) discoverLan(automatic = automatic)
|
||||
else if (!automatic || !bluetoothFallback()) disconnected().apply {
|
||||
route(Route.GALAXY_WIFI, RouteState.FAILED, "Galaxy didn't answer")
|
||||
detail("This phone is on the comma's Wi-Fi, but Galaxy didn't answer.")
|
||||
}
|
||||
}
|
||||
}, "GalaxyProbe").start()
|
||||
}
|
||||
private fun address(origin: String) = origin.removePrefix("http://").removeSuffix(":8082")
|
||||
private fun clearWatchdog() { pageWatchdog?.let { handler.removeCallbacks(it) }; pageWatchdog = null }
|
||||
private fun pageFailed(v: WebView) {
|
||||
if (web !== v) return
|
||||
val failed = origin
|
||||
disconnected().apply {
|
||||
if (failed == Networks.ORIGIN) {
|
||||
route(Route.GALAXY_WIFI, RouteState.FAILED, "Galaxy didn't open")
|
||||
detail("This phone is on the comma's Wi-Fi, but Galaxy didn't answer. Check that Galaxy is turned on in comma settings.")
|
||||
} else {
|
||||
route(Route.HOME_NETWORK, RouteState.FAILED, "No answer at ${address(failed)}")
|
||||
detail("comma didn't answer at ${address(failed)}. Its address may have changed, or comma is off this network.")
|
||||
}
|
||||
}
|
||||
bluetoothFallback()
|
||||
}
|
||||
private fun disconnected(): ConnectScreen {
|
||||
supersedeConnection()
|
||||
screen = null
|
||||
return connectScreen().apply {
|
||||
headline("Connect to comma")
|
||||
detail("Join the comma's Galaxy Wi-Fi, or put this phone on the same Wi-Fi as comma. Galaxy opens as soon as you join.")
|
||||
}
|
||||
}
|
||||
/** The current connect screen, shown on its own; a new one if a page is showing. */
|
||||
private fun connectScreen(): ConnectScreen {
|
||||
val existing = screen
|
||||
if (existing != null) {
|
||||
val parent = existing.view.parent as? ViewGroup
|
||||
if (parent == null || parent.id != android.R.id.content) { parent?.removeView(existing.view); setContentView(existing.view) }
|
||||
return existing
|
||||
}
|
||||
val created = ConnectScreen(this, ::tryRoute, { connect() }, { startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) }, ::openTypedAddress, ::connections)
|
||||
screen = created
|
||||
refreshRoutes(created)
|
||||
setContentView(created.view)
|
||||
return created
|
||||
}
|
||||
private fun refreshRoutes(s: ConnectScreen) {
|
||||
val hotspot = Networks.wifi(this) != null
|
||||
val lan = !hotspot && Networks.wifi(this, false) != null
|
||||
val saved = Networks.localOrigin(prefs.getString("host", "") ?: "")?.takeIf { it != Networks.ORIGIN }
|
||||
val paired = pairing.load() != null
|
||||
s.mode(prefs.getString("transport", "auto"))
|
||||
s.route(Route.GALAXY_WIFI, if (hotspot) RouteState.IDLE else RouteState.UNAVAILABLE, if (hotspot) "Joined" else "Not joined")
|
||||
s.route(Route.HOME_NETWORK, if (lan) RouteState.IDLE else RouteState.UNAVAILABLE, when {
|
||||
hotspot -> "Not needed on Galaxy Wi-Fi"
|
||||
!lan -> "Not on Wi-Fi"
|
||||
saved != null -> "Last found at ${address(saved)}"
|
||||
else -> "Tap to search"
|
||||
})
|
||||
val cached = GalaxyUpdates.store(this).readyRoot != null
|
||||
s.route(Route.BLUETOOTH, if (paired && !pairing.stale()) RouteState.IDLE else RouteState.UNAVAILABLE,
|
||||
if (!paired) "Not paired" else if (pairing.stale()) "Pairing expired, pair again" else if (cached) "Paired, controls only" else "Paired, needs one Wi-Fi visit first")
|
||||
}
|
||||
private fun tryRoute(route: Route) {
|
||||
when (route) {
|
||||
Route.GALAXY_WIFI -> if (Networks.wifi(this) != null) connect(Networks.ORIGIN) else {
|
||||
supersedeConnection(); refreshRoutes(connectScreen()); joinWifi("Join the comma's Galaxy Wi-Fi, then come back")
|
||||
}
|
||||
Route.HOME_NETWORK -> {
|
||||
val generation = supersedeConnection()
|
||||
refreshRoutes(connectScreen())
|
||||
val wifi = Networks.wifi(this, false)
|
||||
val saved = Networks.localOrigin(prefs.getString("host", "") ?: "")?.takeIf { it != Networks.ORIGIN }
|
||||
if (wifi == null) joinWifi("Join the same Wi-Fi as comma, then come back")
|
||||
else if (saved != null) probeWifi(wifi.first, saved, generation, automatic = false)
|
||||
else discoverLan()
|
||||
}
|
||||
Route.BLUETOOTH -> if (pairing.load() != null && !pairing.stale()) connectBluetooth() else {
|
||||
supersedeConnection(); refreshRoutes(connectScreen()); pairPhone()
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun joinWifi(hint: String) {
|
||||
Toast.makeText(this, hint, Toast.LENGTH_LONG).show()
|
||||
startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
|
||||
}
|
||||
private fun openTypedAddress(value: String): String? {
|
||||
val host = Networks.localOrigin(Networks.typedAddress(value)) ?: return "Use comma's private IPv4 address, like 192.168.1.10"
|
||||
connect(host); return null
|
||||
}
|
||||
private fun showWeb(view: WebView, route: Route, label: String, waitForPage: Boolean) {
|
||||
view.setOnApplyWindowInsetsListener { v, insets ->
|
||||
v.setPadding(insets.systemWindowInsetLeft, 0, insets.systemWindowInsetRight, insets.systemWindowInsetBottom); insets
|
||||
}
|
||||
val panel = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setBackgroundColor(Palette.SPACE) }
|
||||
panel.addView(ConnectScreen.webBar(this, route, label) { connections() })
|
||||
panel.addView(view, LinearLayout.LayoutParams(-1, 0, 1f))
|
||||
val overlay = screen
|
||||
if (!waitForPage || overlay == null) { screen = null; setContentView(panel); return }
|
||||
// Keep the connect screen over the page until it has loaded, instead of a blank WebView.
|
||||
(overlay.view.parent as? ViewGroup)?.removeView(overlay.view)
|
||||
setContentView(FrameLayout(this).apply { addView(panel, -1, -1); addView(overlay.view, -1, -1) })
|
||||
}
|
||||
private fun revealWeb() {
|
||||
clearWatchdog()
|
||||
val overlay = screen ?: return
|
||||
screen = null
|
||||
overlay.dismiss()
|
||||
}
|
||||
private fun message(text: String) { if (isFinishing || isDestroyed) return; AlertDialog.Builder(this).setMessage(text).setPositiveButton("OK", null).show() }
|
||||
private fun connections() {
|
||||
ConnectionSheet(this, Transport.of(prefs.getString("transport", "auto")))
|
||||
.onTransport { prefs.edit().putString("transport", it.key).apply(); connect() }
|
||||
.group("Home network") {
|
||||
action("Find comma on this network", "Search this Wi-Fi for Galaxy") { discoverLan(fromMenu = true) }
|
||||
action("Type comma's address", "For routers that block discovery") {
|
||||
val field = EditText(this@MainActivity).apply { setText(prefs.getString("host", Networks.ORIGIN)); setSingleLine() }
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("Local Galaxy address").setView(field).setPositiveButton("Connect") { _, _ ->
|
||||
val host = Networks.localOrigin(Networks.typedAddress(field.text.toString()))
|
||||
if (host == null) message("Use a private IPv4 address on port 8082") else {
|
||||
prefs.edit().putString("host", host).putString("transport", "wifi").apply(); connect(host)
|
||||
}
|
||||
}.setNegativeButton("Cancel", null).show()
|
||||
}
|
||||
}
|
||||
.group("Bluetooth pairing") {
|
||||
action("Add Bluetooth Phone Pairing", "First open Pair phone on comma (Settings > Bluetooth), then tap here") { pairPhone() }
|
||||
action("Forget pairing on this phone") {
|
||||
pairing.forget(); ble?.close(); disconnected()
|
||||
message("Pairing removed from this phone.\n\n$ALSO_FORGET_ON_COMMA")
|
||||
}
|
||||
}
|
||||
.group("Phone GPS") {
|
||||
if (PhoneGpsService.enabled(prefs)) action("Stop sharing phone GPS") { setPhoneGps(false) }
|
||||
else action("Share phone GPS with comma", "Comma uses it for navigation when its own GPS has no fix") { setPhoneGps(true) }
|
||||
}
|
||||
.group("This app") {
|
||||
action("Notification settings") { appNotificationSettings() }
|
||||
action("Refresh Galaxy screens", GalaxyUpdates.store(this@MainActivity).status) {
|
||||
GalaxyUpdates.checkAsync(this@MainActivity) { status -> runOnUiThread { message(status) } }
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
private fun appNotificationSettings() {
|
||||
if (!requestNotificationPermission(1)) startActivity(Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, packageName))
|
||||
}
|
||||
private fun requestNotificationPermission(code: Int): Boolean {
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED &&
|
||||
!prefs.getBoolean("notificationPermissionRequested", false)) {
|
||||
prefs.edit().putBoolean("notificationPermissionRequested", true).apply()
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), code)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
private fun requestAppUpdate(requestedOrigin: String = origin) {
|
||||
val localOrigin = Networks.localOrigin(requestedOrigin)
|
||||
if (bluetoothMode || localOrigin == null) {
|
||||
message("Connect using Galaxy Wi-Fi or LAN to download the app update.")
|
||||
return
|
||||
}
|
||||
if (!packageManager.canRequestPackageInstalls()) {
|
||||
pendingInstallOrigin = localOrigin
|
||||
Toast.makeText(this, "Allow StarPilot to install its downloaded update, then return.", Toast.LENGTH_LONG).show()
|
||||
startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:$packageName")))
|
||||
return
|
||||
}
|
||||
pendingInstallOrigin = null
|
||||
val network = (if (localOrigin == Networks.ORIGIN) Networks.wifi(this) else Networks.wifi(this, false))?.first
|
||||
if (network == null) {
|
||||
message("Reconnect to the same Wi-Fi as comma, then try the update again.")
|
||||
return
|
||||
}
|
||||
if (!AppInstaller.start(this, network, localOrigin)) Toast.makeText(this, "An app update is already in progress.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
private var discovery: LanDiscovery? = null
|
||||
private var discoveryAutomatic = false
|
||||
private var lanPicker: AlertDialog? = null
|
||||
private fun stopDiscovery() {
|
||||
probes.values.forEach { it.disconnect() }; probes.clear()
|
||||
discovery?.close(); discovery = null
|
||||
lanPicker?.dismiss(); lanPicker = null
|
||||
}
|
||||
private fun bluetoothFallback(): Boolean {
|
||||
if (prefs.getString("transport", "auto") != "auto" || pairing.load() == null || pairing.stale()) return false
|
||||
connectBluetooth(automatic = true); return true
|
||||
}
|
||||
/** [fromMenu] keeps the old menu behavior: always confirm the address, then stay on Wi-Fi/LAN. */
|
||||
private fun discoverLan(automatic: Boolean = false, fromMenu: Boolean = false) {
|
||||
val wifi = Networks.wifi(this, false)
|
||||
if (wifi == null) {
|
||||
val text = "Join the same Wi-Fi network as comma first."
|
||||
screen?.route(Route.HOME_NETWORK, RouteState.UNAVAILABLE, "Not on Wi-Fi")
|
||||
if (automatic && bluetoothFallback()) return
|
||||
screen?.detail(text) ?: message(text)
|
||||
return
|
||||
}
|
||||
stopDiscovery()
|
||||
discoveryAutomatic = automatic
|
||||
val generation = connectionGeneration.get()
|
||||
val quickBluetoothFallback = automatic && prefs.getString("transport", "auto") == "auto" && pairing.load() != null
|
||||
val search = LanDiscovery(this, wifi.first, if (quickBluetoothFallback) GalaxyProbe.AUTOMATIC_DISCOVERY_MS else 12000L) { hosts, error ->
|
||||
discovery = null
|
||||
if (!isFinishing && !isDestroyed && generation == connectionGeneration.get()) {
|
||||
fun select(host: String) {
|
||||
val edit = prefs.edit().putString("host", host)
|
||||
if (fromMenu) edit.putString("transport", "wifi")
|
||||
edit.apply(); connect(host)
|
||||
}
|
||||
fun cancel() {
|
||||
if (generation != connectionGeneration.get() || web != null || ble != null) return
|
||||
screen?.route(Route.HOME_NETWORK, RouteState.IDLE, "Tap to search again")
|
||||
if (automatic) bluetoothFallback()
|
||||
}
|
||||
val s = screen
|
||||
if (hosts.isEmpty()) {
|
||||
val text = error ?: "No comma answered on this Wi-Fi. Check that Galaxy is on and comma is on the same network. " +
|
||||
"A new install needs a few minutes parked with internet before comma can be found. " +
|
||||
"If your router blocks discovery, type comma's address instead."
|
||||
s?.route(Route.HOME_NETWORK, RouteState.FAILED, "No comma found")
|
||||
if (!(automatic && bluetoothFallback())) {
|
||||
if (s != null) { s.headline("Connect to comma"); s.detail(text) } else message(text)
|
||||
}
|
||||
} else if (hosts.size == 1 && !fromMenu) select(hosts.single())
|
||||
else {
|
||||
s?.route(Route.HOME_NETWORK, RouteState.LIVE, "${hosts.size} found")
|
||||
s?.headline("Choose your comma")
|
||||
val picker = AlertDialog.Builder(this).setTitle("Choose your comma on this trusted LAN")
|
||||
.setItems(hosts.map(::address).toTypedArray()) { _, which -> if (generation == connectionGeneration.get()) select(hosts[which]) }
|
||||
.setNegativeButton("Cancel") { _, _ -> cancel() }.setOnCancelListener { cancel() }.create()
|
||||
picker.setOnDismissListener { if (lanPicker === picker) lanPicker = null }
|
||||
lanPicker = picker; picker.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
discovery = search
|
||||
val s = screen
|
||||
if (s != null) {
|
||||
s.headline("Finding your comma")
|
||||
s.route(Route.HOME_NETWORK, RouteState.TRYING, "Searching…")
|
||||
s.detail(if (quickBluetoothFallback) "Checking this Wi-Fi for comma before trying Bluetooth."
|
||||
else "Looking for comma on this Wi-Fi network. This takes up to 12 seconds.")
|
||||
} else Toast.makeText(this, "Looking for comma on LAN…", Toast.LENGTH_LONG).show()
|
||||
search.start()
|
||||
}
|
||||
private fun savePairing(value: JSONObject) {
|
||||
require(value.getString("type") == "galaxy-bluetooth" && value.getInt("version") == 1)
|
||||
val hex = value.getString("key")
|
||||
require(hex.matches(Regex("[0-9a-fA-F]{64}")))
|
||||
pairing.save(hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray(), value.optString("id").ifEmpty { null })
|
||||
}
|
||||
/** How comma lists this phone under Settings → Bluetooth, e.g. "Danny's Pixel 8". */
|
||||
private fun phoneName(): String =
|
||||
(Settings.Global.getString(contentResolver, Settings.Global.DEVICE_NAME)?.trim()?.takeIf { it.isNotEmpty() }
|
||||
?: "${Build.MANUFACTURER} ${Build.MODEL}").take(40)
|
||||
private fun phoneHello(): JSONObject = JSONObject().put("name", phoneName()).apply { pairing.previousId()?.let { put("replaces", it) } }
|
||||
/** One step for the app and music: comma's open pairing window gives this phone its key, then bonds it for music. */
|
||||
private val ALSO_FORGET_ON_COMMA = "Also forget this phone on comma (Settings > Bluetooth, or Galaxy > Bluetooth), or comma keeps the old pairing and may fail to pair this phone again."
|
||||
private val ALSO_FORGET_ON_PHONE = "Also forget comma in this phone's Bluetooth settings before pairing again, so the old Bluetooth bond doesn't get in the way."
|
||||
private val PAIR_STEPS = "On comma open Settings > Bluetooth > Pair phone (or Galaxy > Bluetooth > Pair phone) and keep that screen open."
|
||||
/** Without a Wi-Fi/LAN route the app cannot open comma's window itself, so say so before waiting for it. */
|
||||
private fun askToOpenWindow() {
|
||||
if (isFinishing || isDestroyed) return
|
||||
AlertDialog.Builder(this).setTitle("Open Pair phone on comma first")
|
||||
.setMessage("$PAIR_STEPS\n\nComma's window stays open for 2 minutes. Tap Continue once it shows.")
|
||||
.setPositiveButton("Continue") { _, _ -> pairPhone(confirmed = true) }
|
||||
.setNegativeButton("Cancel", null).show()
|
||||
}
|
||||
private fun pairPhone(confirmed: Boolean = false) {
|
||||
if (pairProgress != null || autoPairing.get()) return
|
||||
val permissions = if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
|
||||
else arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
if (permissions.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }) { requestPermissions(permissions, 5); return }
|
||||
if (!confirmed && Networks.commaLan(this) == null) { askToOpenWindow(); return }
|
||||
if (!autoPairing.compareAndSet(false, true)) return
|
||||
val generation = supersedeConnection()
|
||||
pairCancelled = false
|
||||
showPairProgress("Checking that comma is ready to pair…", 0)
|
||||
connectScreen().apply {
|
||||
refreshRoutes(this)
|
||||
headline("Pairing with comma")
|
||||
route(Route.BLUETOOTH, RouteState.TRYING, "Pairing…")
|
||||
detail("$PAIR_STEPS\nKeep Bluetooth on for comma and this phone.")
|
||||
}
|
||||
Thread {
|
||||
try {
|
||||
// Already on comma's Wi-Fi/LAN: open its pairing window ourselves so nobody has to touch comma.
|
||||
var windowNote = ""
|
||||
var notReady: CommaReadiness? = null
|
||||
Networks.commaLan(this)?.let { (network, origin) ->
|
||||
// Don't start a Bluetooth pairing comma can't take yet; wait out a boot or bridge restart, or say what to fix.
|
||||
if (pairCancelled) return@Thread
|
||||
notReady = LanPairing.waitUntilReady(network, origin) { text ->
|
||||
showPairProgress(text, 0)
|
||||
runOnUiThread { if (generation == connectionGeneration.get()) screen?.detail("Waiting for comma's Bluetooth to be ready…\n$text") }
|
||||
}
|
||||
if (notReady != null) return@let
|
||||
if (pairCancelled) return@Thread
|
||||
showPairProgress("Opening comma’s pairing window over Wi-Fi…", 1)
|
||||
val why = LanPairing.openWindow(network, origin)
|
||||
if (why != null) {
|
||||
android.util.Log.w("GalaxyPair", "Could not open comma's window over Wi-Fi: $why")
|
||||
if (!pairCancelled) runOnUiThread { message("Couldn't open comma's pairing window over Wi-Fi ($why).\n\n$PAIR_STEPS Then try again.") }
|
||||
return@Thread
|
||||
}
|
||||
windowNote = "Opened comma's pairing window over Wi-Fi.\n"
|
||||
runOnUiThread { if (generation == connectionGeneration.get()) screen?.detail(windowNote.trim()) }
|
||||
}
|
||||
notReady?.let { blocked ->
|
||||
hidePairProgress()
|
||||
runOnUiThread {
|
||||
if (generation == connectionGeneration.get()) {
|
||||
screen?.headline("Comma isn't ready to pair")
|
||||
pairingNotice("Comma isn't ready to pair yet: ${blocked.message}\nTry Add Bluetooth Phone Pairing again in a moment.", pairing.load() != null)
|
||||
}
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
if (pairCancelled) return@Thread
|
||||
val transport = BleTransport(this, null)
|
||||
pairTransport = transport
|
||||
transport.onPhase = { text ->
|
||||
showPairProgress(text, if (text.startsWith("Pairing:")) 3 else 2)
|
||||
runOnUiThread { if (generation == connectionGeneration.get()) screen?.detail(windowNote + text) }
|
||||
}
|
||||
ble = transport
|
||||
try {
|
||||
val claim = ClaimPairing.claim(transport, phoneName())
|
||||
if (pairCancelled || generation != connectionGeneration.get()) return@Thread
|
||||
pairing.save(claim.key, claim.id.ifEmpty { null })
|
||||
transport.close()
|
||||
runOnUiThread { if (generation == connectionGeneration.get()) screen?.detail("Paired. Setting up music: tap Pair if your phone asks.") }
|
||||
showPairProgress("Galaxy paired. Approve the Bluetooth music prompt on this phone if it asks.", 4)
|
||||
val outcome = bondMusic(claim.adapterAddress)
|
||||
if (outcome == MusicBond.Outcome.PAIRED || outcome == MusicBond.Outcome.ALREADY_PAIRED) pairing.rememberMusic(claim.adapterAddress)
|
||||
if (pairCancelled || generation != connectionGeneration.get()) return@Thread
|
||||
runOnUiThread {
|
||||
if (generation != connectionGeneration.get()) return@runOnUiThread
|
||||
MusicBond.message(outcome)?.let { message(it) }
|
||||
connectBluetooth()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
transport.close()
|
||||
if (pairCancelled) return@Thread
|
||||
android.util.Log.w("GalaxyPair", "Pairing failed", e)
|
||||
runOnUiThread {
|
||||
if (generation == connectionGeneration.get()) {
|
||||
screen?.headline("Pairing didn't finish")
|
||||
pairingNotice("Couldn't pair: ${e.message ?: "comma didn't answer"}", pairing.load() != null)
|
||||
} else android.util.Log.w("GalaxyPair", "Pairing result dropped: a newer connection attempt replaced it")
|
||||
}
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
} finally {
|
||||
autoPairing.set(false)
|
||||
pairTransport = null
|
||||
hidePairProgress()
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
/** Forgetting comma in the phone's Bluetooth settings also ends the app pairing, like forgetting a phone on comma does. */
|
||||
private val bondWatcher = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context, intent: Intent) {
|
||||
val device = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(android.bluetooth.BluetoothDevice.EXTRA_DEVICE, android.bluetooth.BluetoothDevice::class.java)
|
||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(android.bluetooth.BluetoothDevice.EXTRA_DEVICE)
|
||||
val state = intent.getIntExtra(android.bluetooth.BluetoothDevice.EXTRA_BOND_STATE, -1)
|
||||
if (CommaBond.forgotten(pairing.musicAddress(), device?.address, state)) commaBondEnded("You forgot comma in this phone's Bluetooth settings")
|
||||
}
|
||||
}
|
||||
private fun commaBondEnded(why: String) {
|
||||
if (pairing.load() == null) return
|
||||
android.util.Log.i("GalaxyPair", "Dropping the app pairing: $why")
|
||||
pairing.forget(); ble?.close()
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
message("$why, so the app pairing was removed too.\n\n$ALSO_FORGET_ON_COMMA\n\nTo set it up again: $PAIR_STEPS Then tap Add Bluetooth Phone Pairing.")
|
||||
if (bluetoothMode) disconnected()
|
||||
}
|
||||
}
|
||||
/** Catches a forget done while the app was closed. */
|
||||
private fun checkMusicBond() {
|
||||
val address = pairing.musicAddress() ?: return
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
|
||||
val bonded = runCatching { getSystemService(android.bluetooth.BluetoothManager::class.java)?.adapter?.bondedDevices?.map { it.address }?.toSet() }.getOrNull() ?: return
|
||||
if (CommaBond.missing(address, bonded)) commaBondEnded("Comma is no longer in this phone's Bluetooth devices")
|
||||
}
|
||||
private val autoPairing = java.util.concurrent.atomic.AtomicBoolean()
|
||||
private var autoPairAsked = false
|
||||
private fun bluetoothPermissions() = if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
|
||||
else arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
private var pairProgress: PairingProgressDialog? = null
|
||||
@Volatile private var pairCancelled = false
|
||||
@Volatile private var pairTransport: BleTransport? = null
|
||||
private fun showPairProgress(text: String, stage: Int? = null) = runOnUiThread {
|
||||
if (isFinishing || isDestroyed || pairCancelled) return@runOnUiThread
|
||||
val dialog = pairProgress ?: PairingProgressDialog(this) {
|
||||
pairCancelled = true
|
||||
pairTransport?.close()
|
||||
pairProgress = null
|
||||
}.also { pairProgress = it }
|
||||
dialog.update(text, stage)
|
||||
}
|
||||
private fun hidePairProgress() = runOnUiThread { pairProgress?.dismiss(); pairProgress = null }
|
||||
|
||||
/** Galaxy just opened over Wi-Fi/LAN and this phone has no working comma pairing: offer to pair right away, once per launch. */
|
||||
private fun autoPairIfNeeded() {
|
||||
if (bluetoothMode || (pairing.load() != null && !pairing.stale()) || autoPairAsked || !prefs.getBoolean("autoPair", true)) return
|
||||
autoPairAsked = true
|
||||
if (isFinishing || isDestroyed) return
|
||||
val again = pairing.load() != null
|
||||
val dialog = AlertDialog.Builder(this, R.style.AppDialog)
|
||||
.setTitle(if (again) "Add Bluetooth phone pairing again?" else "Add Bluetooth phone pairing?")
|
||||
.setNegativeButton("Not now", null)
|
||||
.setPositiveButton("Add pairing") { _, _ -> startAutoPair() }
|
||||
.create()
|
||||
val themed = dialog.context
|
||||
val padding = (24 * resources.displayMetrics.density).toInt()
|
||||
val content = LinearLayout(themed).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(padding, padding / 2, padding, padding / 2)
|
||||
}
|
||||
content.addView(TextView(themed).apply {
|
||||
textSize = 16f
|
||||
setTextColor(Palette.ON)
|
||||
text = (if (again) "Comma no longer recognizes this phone's pairing. Pair again to restore Bluetooth Galaxy and music."
|
||||
else "Pair this phone to use Galaxy without Wi-Fi and set up Bluetooth music.") +
|
||||
"\n\n1. Keep comma parked, stay connected over Wi-Fi, and turn on Bluetooth on both devices." +
|
||||
"\n\n2. Tap Add pairing. The app opens comma's pairing window automatically." +
|
||||
"\n\n3. Allow Nearby devices if asked, then approve the Bluetooth pairing prompt on this phone. Confirm the code matches if one is shown." +
|
||||
"\n\n4. Wait for the app to confirm pairing is complete. If needed, choose comma as your phone's Bluetooth audio output."
|
||||
})
|
||||
content.addView(CheckBox(themed).apply {
|
||||
text = "Don't ask again"
|
||||
setOnCheckedChangeListener { _, checked -> prefs.edit().putBoolean("autoPair", !checked).apply() }
|
||||
})
|
||||
dialog.setView(ScrollView(themed).apply { addView(content) })
|
||||
dialog.show()
|
||||
}
|
||||
private fun startAutoPair() {
|
||||
val permissions = bluetoothPermissions()
|
||||
if (permissions.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }) requestPermissions(permissions, 6) else runAutoPair()
|
||||
}
|
||||
private fun runAutoPair() {
|
||||
val lan = Networks.commaLan(this) ?: return message("This phone isn't connected to comma over Wi-Fi right now. Join comma's Wi-Fi, then tap Add Bluetooth Phone Pairing in the menu.")
|
||||
if (!autoPairing.compareAndSet(false, true)) return
|
||||
pairCancelled = false
|
||||
showPairProgress("Checking that comma is ready to pair…", 0)
|
||||
Thread {
|
||||
try {
|
||||
LanPairing.waitUntilReady(lan.first, lan.second) { text -> showPairProgress("Waiting for comma's Bluetooth to be ready…\n$text") }?.let { blocked ->
|
||||
android.util.Log.w("GalaxyPair", "Comma not ready to pair: ${blocked.code}")
|
||||
hidePairProgress()
|
||||
if (!pairCancelled) runOnUiThread { message("Comma isn't ready to pair yet: ${blocked.message}\n\nTry Add Bluetooth Phone Pairing in the menu in a moment.") }
|
||||
return@Thread
|
||||
}
|
||||
if (pairCancelled) return@Thread
|
||||
showPairProgress("Opening comma's pairing window over Wi-Fi…", 1)
|
||||
LanPairing.openWindow(lan.first, lan.second)?.let { why ->
|
||||
android.util.Log.w("GalaxyPair", "Could not open comma's window over Wi-Fi: $why")
|
||||
hidePairProgress()
|
||||
if (!pairCancelled) runOnUiThread { message("Couldn't open comma's pairing window over Wi-Fi ($why).\n\n$PAIR_STEPS Then tap Add Bluetooth Phone Pairing in the menu.") }
|
||||
return@Thread
|
||||
}
|
||||
if (pairCancelled) return@Thread
|
||||
val transport = BleTransport(this, null)
|
||||
pairTransport = transport
|
||||
transport.onPhase = { text -> showPairProgress(text, if (text.startsWith("Pairing:")) 3 else 2) }
|
||||
try {
|
||||
val claim = ClaimPairing.claim(transport, phoneName())
|
||||
if (pairCancelled) return@Thread
|
||||
pairing.save(claim.key, claim.id.ifEmpty { null })
|
||||
transport.close()
|
||||
showPairProgress("Galaxy paired. Approve the Bluetooth music prompt on this phone if it asks.", 4)
|
||||
val outcome = bondMusic(claim.adapterAddress)
|
||||
if (outcome == MusicBond.Outcome.PAIRED || outcome == MusicBond.Outcome.ALREADY_PAIRED) pairing.rememberMusic(claim.adapterAddress)
|
||||
if (!pairCancelled) runOnUiThread { message(MusicBond.message(outcome) ?: "Paired with comma. Bluetooth Galaxy is ready.") }
|
||||
} catch (e: Exception) {
|
||||
transport.close()
|
||||
if (pairCancelled) return@Thread
|
||||
android.util.Log.w("GalaxyPair", "Pairing failed", e)
|
||||
runOnUiThread { message("Couldn't pair: ${e.message ?: "comma didn't answer"}\n\n$PAIR_STEPS Then tap Add Bluetooth Phone Pairing in the menu.") }
|
||||
}
|
||||
} finally {
|
||||
// Whatever happened, never leave the progress dialog up.
|
||||
autoPairing.set(false); pairTransport = null; hidePairProgress()
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
private fun bondMusic(address: String): MusicBond.Outcome {
|
||||
val adapter = getSystemService(android.bluetooth.BluetoothManager::class.java)?.adapter
|
||||
if (adapter == null || !adapter.isEnabled) return MusicBond.Outcome.FAILED
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return MusicBond.Outcome.FAILED
|
||||
return try {
|
||||
// Comma presents as a speaker while its window is open. Seeing it in a normal Bluetooth scan first makes
|
||||
// Android bond over classic audio Bluetooth, the way tapping comma in Bluetooth settings does.
|
||||
runCatching { discoverComma(adapter, address) }.onFailure { android.util.Log.w("GalaxyPair", "Bluetooth scan before music bond failed", it) }
|
||||
MusicBond({ adapter.bondedDevices.map { it.address.uppercase() }.toSet() }, {
|
||||
adapter.getRemoteDevice(it).createBond().also { started -> android.util.Log.i("GalaxyPair", "createBond($it) started=$started") }
|
||||
}).run(address)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("GalaxyPair", "Music bond failed", e)
|
||||
MusicBond.Outcome.FAILED
|
||||
}
|
||||
}
|
||||
/** Runs one classic Bluetooth scan until [address] shows up or [millis] passes. Blocks; call from a worker thread. */
|
||||
private fun discoverComma(adapter: android.bluetooth.BluetoothAdapter, address: String, millis: Long = 10000) {
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) return
|
||||
val seen = java.util.concurrent.CountDownLatch(1)
|
||||
val receiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context, intent: Intent) {
|
||||
val device = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(android.bluetooth.BluetoothDevice.EXTRA_DEVICE, android.bluetooth.BluetoothDevice::class.java)
|
||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(android.bluetooth.BluetoothDevice.EXTRA_DEVICE)
|
||||
if (device?.address.equals(address, ignoreCase = true)) seen.countDown()
|
||||
}
|
||||
}
|
||||
val filter = android.content.IntentFilter(android.bluetooth.BluetoothDevice.ACTION_FOUND)
|
||||
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, filter, RECEIVER_EXPORTED) else registerReceiver(receiver, filter)
|
||||
try {
|
||||
if (adapter.startDiscovery()) seen.await(millis, java.util.concurrent.TimeUnit.MILLISECONDS)
|
||||
} finally {
|
||||
runCatching { adapter.cancelDiscovery() }
|
||||
runCatching { unregisterReceiver(receiver) }
|
||||
}
|
||||
}
|
||||
/** Pairing results appear on the connect screen when it is showing, otherwise in a dialog over Galaxy. */
|
||||
private fun phoneGpsPermissions(): Array<String> = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) +
|
||||
(if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) else emptyArray()) +
|
||||
(if (Build.VERSION.SDK_INT >= 33) arrayOf(Manifest.permission.POST_NOTIFICATIONS) else emptyArray())
|
||||
private fun setPhoneGps(enabled: Boolean) {
|
||||
if (!enabled) { prefs.edit().putBoolean("phoneGps", false).apply(); stopService(Intent(this, PhoneGpsService::class.java)); return }
|
||||
val missing = phoneGpsPermissions().filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (missing.isNotEmpty()) { requestPermissions(missing.toTypedArray(), 4); return }
|
||||
prefs.edit().putBoolean("phoneGps", true).apply()
|
||||
startForegroundService(Intent(this, PhoneGpsService::class.java))
|
||||
message("Sharing phone GPS. Keep this app's notification while driving; comma uses it only when its own GPS has no fix.")
|
||||
}
|
||||
private fun pairingNotice(text: String, paired: Boolean) {
|
||||
val s = screen ?: return message(text)
|
||||
s.detail(text)
|
||||
s.route(Route.BLUETOOTH, if (paired) RouteState.IDLE else RouteState.UNAVAILABLE, if (paired) "Paired, controls only" else "Not paired")
|
||||
}
|
||||
private fun connectBluetooth(automatic: Boolean = false) {
|
||||
val generation = supersedeConnection()
|
||||
bluetoothAttemptAutomatic = automatic
|
||||
val key = pairing.load()
|
||||
if (key == null) {
|
||||
disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.UNAVAILABLE, "Not paired")
|
||||
detail("Pair first. $PAIR_STEPS Then tap Add Bluetooth Phone Pairing here.")
|
||||
}
|
||||
return
|
||||
}
|
||||
if (pairing.stale()) {
|
||||
// Comma stopped recognizing this phone; retrying cannot fix that, so wait for a new pairing instead.
|
||||
disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.FAILED, "Pairing expired")
|
||||
detail("Comma no longer recognizes this phone (it was forgotten there). $ALSO_FORGET_ON_PHONE $PAIR_STEPS Then tap Add Bluetooth Phone Pairing here.")
|
||||
}
|
||||
return
|
||||
}
|
||||
if (GalaxyUpdates.store(this).readyRoot == null) {
|
||||
// Bluetooth Galaxy serves pages saved from comma; the first download needs Wi-Fi/LAN.
|
||||
disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.FAILED, "Needs one Wi-Fi visit first")
|
||||
detail(GalaxyAssetStore.NOT_DOWNLOADED + " After that, Bluetooth Galaxy works anywhere.")
|
||||
}
|
||||
return
|
||||
}
|
||||
val permissions = if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
|
||||
else arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
if (permissions.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }) { requestPermissions(permissions, 2); return }
|
||||
connectScreen().apply {
|
||||
refreshRoutes(this)
|
||||
headline("Connecting over Bluetooth")
|
||||
route(Route.BLUETOOTH, RouteState.TRYING, "Connecting…")
|
||||
detail("Keep Bluetooth on for comma and this phone. Bluetooth opens Galaxy controls; maps and video need Wi-Fi.")
|
||||
}
|
||||
Thread {
|
||||
var transport = BleTransport(this, key, phoneHello())
|
||||
if (generation != connectionGeneration.get()) { transport.close(); return@Thread }
|
||||
ble = transport
|
||||
try {
|
||||
val remembered = pairing.deviceAddress()
|
||||
val device = try { transport.connect(remembered) } catch (first: Exception) {
|
||||
if (remembered == null || generation != connectionGeneration.get()) throw first
|
||||
transport.close()
|
||||
transport = BleTransport(this, key, phoneHello())
|
||||
ble = transport
|
||||
transport.connect()
|
||||
}
|
||||
pairing.rememberDevice(device)
|
||||
runOnUiThread { if (!isFinishing && generation == connectionGeneration.get()) showBluetooth(transport) else transport.close() }
|
||||
} catch (e: Exception) {
|
||||
transport.close()
|
||||
if (e is PairingNotRecognized) { pairing.markStale(); android.util.Log.w("GalaxyPair", "Pairing not recognized by comma: ${e.message}") }
|
||||
runOnUiThread {
|
||||
if (e is PairingNotRecognized && !isFinishing && generation == connectionGeneration.get()) disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.FAILED, "Pairing expired")
|
||||
detail("Comma no longer recognizes this phone (${e.message}). $ALSO_FORGET_ON_PHONE $PAIR_STEPS Then tap Add Bluetooth Phone Pairing here.")
|
||||
} else if (!isFinishing && generation == connectionGeneration.get()) disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.FAILED, "Didn't connect")
|
||||
detail("Bluetooth didn't connect: ${e.message ?: "comma didn't answer"}. Check that Bluetooth is on in comma settings and comma is nearby.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
override fun onRequestPermissionsResult(code: Int, permissions: Array<out String>, results: IntArray) {
|
||||
super.onRequestPermissionsResult(code, permissions, results)
|
||||
if ((code == 1 || code == 7) && results.firstOrNull() == PackageManager.PERMISSION_GRANTED) AppUpdates.checkAsync(this)
|
||||
if (code == 7) connect(Networks.localOrigin(intent.getStringExtra(AppUpdates.ORIGIN_EXTRA) ?: ""))
|
||||
if (code == 5 && results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED }) pairPhone()
|
||||
if (code == 6) {
|
||||
if (results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED }) runAutoPair()
|
||||
else message("Pairing needs the Nearby devices permission. Allow it, then tap Add Bluetooth Phone Pairing in the menu.")
|
||||
}
|
||||
if (code == 4) {
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
prefs.edit().putBoolean("phoneGps", true).apply()
|
||||
startForegroundService(Intent(this, PhoneGpsService::class.java))
|
||||
} else message("Allow precise location to share phone GPS with comma.")
|
||||
}
|
||||
if (code == 2) { if (results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED }) connectBluetooth(bluetoothAttemptAutomatic)
|
||||
else disconnected().apply {
|
||||
route(Route.BLUETOOTH, RouteState.FAILED, "Needs permission")
|
||||
detail("Allow Nearby devices to connect over Bluetooth. Wi-Fi and LAN still work without it.")
|
||||
} }
|
||||
}
|
||||
private fun showBluetooth(transport: BleTransport) {
|
||||
bluetoothMode = true
|
||||
origin = cachedOrigin
|
||||
val galaxy = GalaxyUpdates.store(this)
|
||||
val galaxyRoot = galaxy.readyRoot.also { galaxy.inUseRoot = it } ?: return
|
||||
val view = WebView(this); web = view
|
||||
view.setBackgroundColor(Color.rgb(7, 7, 18))
|
||||
view.settings.javaScriptEnabled = true; view.settings.domStorageEnabled = true
|
||||
view.settings.allowFileAccess = false; view.settings.allowContentAccess = false
|
||||
view.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
view.addJavascriptInterface(Bridge(), "StarPilotApp")
|
||||
view.addJavascriptInterface(object {
|
||||
@JavascriptInterface fun cancel(id: String) { jobs.remove(id)?.cancel(false); worker.purge() }
|
||||
@JavascriptInterface fun request(id: String, raw: String) {
|
||||
if (id.length > 20 || raw.length > 1500000 || web !== view) return
|
||||
fun reply(value: JSONObject) { runOnUiThread {
|
||||
if (web === view) view.evaluateJavascript("window.__galaxyBleReply(${JSONObject.quote(id)},${value});", null)
|
||||
} }
|
||||
val task = FutureTask<Unit> {
|
||||
try {
|
||||
if (web !== view) return@FutureTask
|
||||
val input = JSONObject(raw)
|
||||
val path = input.getString("path")
|
||||
require(path.startsWith("/api/") && !path.contains('\\') && !path.contains("..") && !path.contains("//"))
|
||||
reply(transport.request(input))
|
||||
} catch (e: Exception) { reply(JSONObject().put("error", e.message ?: "Bluetooth failed; check the result before retrying changes.")) }
|
||||
finally { jobs.remove(id) }
|
||||
}
|
||||
jobs[id] = task
|
||||
try { worker.execute(task) } catch (_: RejectedExecutionException) { jobs.remove(id); reply(JSONObject().put("error", "Bluetooth is busy. Wait for the current request.")) }
|
||||
}
|
||||
}, "StarPilotBLE")
|
||||
view.webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(v: WebView, r: WebResourceRequest) = r.url.scheme != "https" || r.url.host != "galaxy-app.invalid"
|
||||
override fun shouldInterceptRequest(v: WebView, r: WebResourceRequest): WebResourceResponse {
|
||||
fun response(type: String, data: ByteArray, status: Int = 200) = WebResourceResponse(type, "UTF-8", status, if (status == 200) "OK" else "Unavailable", mapOf("Cache-Control" to "no-store"), ByteArrayInputStream(data))
|
||||
if (r.url.scheme != "https" || r.url.host != "galaxy-app.invalid" || r.url.port != -1) return response("text/plain", byteArrayOf(), 403)
|
||||
val path = r.url.path ?: "/"
|
||||
if (path.startsWith("/api/")) return response("application/json", "{\"error\":\"Media and direct downloads are not available over Bluetooth. Connect using Galaxy Wi-Fi or LAN.\",\"code\":\"bluetooth_unavailable\"}".toByteArray(), 501)
|
||||
if (path.contains("..") || path.contains('\\') || path.contains("//")) return response("text/plain", byteArrayOf(), 403)
|
||||
return try {
|
||||
var data = when (path) {
|
||||
"/data/runtime.json" -> "{\"schemaVersion\":1,\"monitor\":\"local\"}".toByteArray()
|
||||
"/bluetooth-fetch.js" -> assets.open("bluetooth-fetch.js").use { it.readBytes() }
|
||||
else -> (if (path == "/") "index.html" else path.removePrefix("/")).let { file ->
|
||||
File(galaxyRoot, file).readBytes()
|
||||
}
|
||||
}
|
||||
if (path == "/" || path == "/index.html") data = String(data).replace("<head>", "<head><script src=\"/bluetooth-fetch.js\"></script>").toByteArray()
|
||||
val type = when {
|
||||
path == "/" || path.endsWith(".html") -> "text/html"
|
||||
path.endsWith(".js") -> "text/javascript"
|
||||
path.endsWith(".css") -> "text/css"
|
||||
path.endsWith(".json") -> "application/json"
|
||||
path.endsWith(".svg") -> "image/svg+xml"
|
||||
else -> java.net.URLConnection.guessContentTypeFromName(path) ?: "application/octet-stream"
|
||||
}
|
||||
response(type, data)
|
||||
} catch (_: Exception) { response("text/plain", byteArrayOf(), 404) }
|
||||
}
|
||||
override fun onPageFinished(v: WebView, url: String) { if (web === v) share = null }
|
||||
}
|
||||
showWeb(view, Route.BLUETOOTH, "Bluetooth, controls only", waitForPage = false)
|
||||
try { worker.execute { runCatching {
|
||||
val reply = transport.request(JSONObject().put("method", "GET").put("path", "/api/software/status?history=0").put("headers", JSONObject()).put("body", ""))
|
||||
if (reply.optInt("status") == 200 && GalaxyUpdates.olderThanComma(this, JSONObject(String(Base64.getDecoder().decode(reply.optString("body")))))) {
|
||||
runOnUiThread { if (web === view) Toast.makeText(this, "Galaxy screens are from an older comma build. Connect over Wi-Fi to refresh.", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
} } } catch (_: RejectedExecutionException) {}
|
||||
view.loadUrl(if (share != null) "$origin/?share=${Uri.encode(share)}#/navigation" else "$origin/#/galaxy")
|
||||
}
|
||||
inner class Bridge {
|
||||
@JavascriptInterface fun bluetooth() = bluetoothMode
|
||||
@JavascriptInterface fun connectionOptions() { runOnUiThread { connections() } }
|
||||
@JavascriptInterface fun version() = BuildConfig.VERSION_NAME
|
||||
@JavascriptInterface fun installUpdate() { runOnUiThread { requestAppUpdate() } }
|
||||
@JavascriptInterface fun uplinkState() = JSONObject().put("enabled", prefs.getBoolean("enabled", false)).put("autoStart", prefs.getBoolean("autoStart", false))
|
||||
.put("bytes", if (prefs.getString("day", "") == java.time.LocalDate.now().toString()) prefs.getLong("bytes", 0) else 0).toString()
|
||||
@JavascriptInterface fun setUplinkEnabled(enabled: Boolean) { runOnUiThread {
|
||||
prefs.edit().putBoolean("enabled", enabled).apply()
|
||||
if (enabled) startForegroundService(Intent(this@MainActivity, UplinkService::class.java))
|
||||
else stopService(Intent(this@MainActivity, UplinkService::class.java))
|
||||
} }
|
||||
@JavascriptInterface fun setAutoStart(enabled: Boolean) { prefs.edit().putBoolean("autoStart", enabled).apply() }
|
||||
@JavascriptInterface fun openWifiSettings() { runOnUiThread { startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) } }
|
||||
}
|
||||
@Deprecated("Legacy back handling") override fun onBackPressed() { if (web?.canGoBack() == true) web?.goBack() else super.onBackPressed() }
|
||||
override fun onResume() {
|
||||
super.onResume(); resumed = true; recovery.resumed(); AppUpdates.checkAsync(this); checkMusicBond()
|
||||
pendingInstallOrigin?.let { if (packageManager.canRequestPackageInstalls()) requestAppUpdate(it) }
|
||||
}
|
||||
override fun onPause() { resumed = false; super.onPause() }
|
||||
override fun onStop() {
|
||||
recovery.stopped(if (discovery != null || lanPicker != null) discoveryAutomatic else null, web == null && ble == null)
|
||||
super.onStop()
|
||||
}
|
||||
override fun onDestroy() {
|
||||
pairCancelled = true; pairTransport?.close(); hidePairProgress()
|
||||
stopDiscovery(); clearWatchdog(); handler.removeCallbacksAndMessages(null)
|
||||
runCatching { Networks.manager(this).unregisterNetworkCallback(wifiWatcher) }
|
||||
runCatching { unregisterReceiver(bondWatcher) }
|
||||
connectionGeneration.incrementAndGet(); ble?.close(); worker.shutdownNow()
|
||||
web?.destroy(); Networks.manager(this).bindProcessToNetwork(null); super.onDestroy()
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
/** After the app is paired, also bond this phone with comma for Bluetooth music. Comma's open window accepts it; Android asks the user once. */
|
||||
class MusicBond(
|
||||
private val bonded: () -> Set<String>,
|
||||
private val bond: (address: String) -> Boolean,
|
||||
private val pause: (millis: Long) -> Unit = { Thread.sleep(it) },
|
||||
private val attempts: Int = 180,
|
||||
) {
|
||||
enum class Outcome { PAIRED, ALREADY_PAIRED, UNSUPPORTED, FAILED }
|
||||
|
||||
fun run(address: String): Outcome {
|
||||
// An older comma sends no Bluetooth address.
|
||||
if (!ADDRESS.matches(address)) return Outcome.UNSUPPORTED
|
||||
val comma = address.uppercase()
|
||||
if (comma in bonded()) return Outcome.ALREADY_PAIRED
|
||||
if (!bond(comma)) return Outcome.FAILED
|
||||
repeat(attempts) {
|
||||
if (comma in bonded()) return Outcome.PAIRED
|
||||
pause(500)
|
||||
}
|
||||
return Outcome.FAILED
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val ADDRESS = Regex("(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){5}")
|
||||
|
||||
fun message(outcome: Outcome): String? = when (outcome) {
|
||||
Outcome.PAIRED -> "Paired with comma. For music, choose comma as this phone's media audio output."
|
||||
Outcome.ALREADY_PAIRED -> "Paired with comma. Music was already set up on this phone."
|
||||
Outcome.UNSUPPORTED -> null
|
||||
Outcome.FAILED -> "The app is paired, but music wasn't set up. Open Pair phone on comma again (Settings > Bluetooth), then tap Add Bluetooth Phone Pairing here."
|
||||
}
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.content.Context
|
||||
import android.net.*
|
||||
import java.net.Inet4Address
|
||||
|
||||
object Networks {
|
||||
const val ORIGIN = "http://172.31.254.1:8082"
|
||||
const val PROTOCOL = 1
|
||||
fun manager(context: Context) = context.getSystemService(ConnectivityManager::class.java)
|
||||
fun wifi(context: Context, hotspotOnly: Boolean = true): Pair<Network, Inet4Address>? {
|
||||
val cm = manager(context)
|
||||
return cm.allNetworks.firstNotNullOfOrNull { network ->
|
||||
if (cm.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) != true) return@firstNotNullOfOrNull null
|
||||
cm.getLinkProperties(network)?.linkAddresses?.map { it.address }?.filterIsInstance<Inet4Address>()
|
||||
?.firstOrNull { it.isSiteLocalAddress && (!hotspotOnly || it.hostAddress!!.startsWith("172.31.254.")) }
|
||||
?.let { network to it }
|
||||
}
|
||||
}
|
||||
/** The Wi-Fi network that reaches comma and its origin: the hotspot, else the LAN host the app saved when it found comma. */
|
||||
fun commaLan(context: Context): Pair<Network, String>? {
|
||||
val hotspot = wifi(context)
|
||||
val network = hotspot ?: wifi(context, false) ?: return null
|
||||
val saved = context.getSharedPreferences("companion", Context.MODE_PRIVATE).getString("host", "") ?: ""
|
||||
val origin = if (hotspot != null) ORIGIN else localOrigin(saved)?.takeIf { it != ORIGIN } ?: return null
|
||||
return network.first to origin
|
||||
}
|
||||
/** Accept what people type: "192.168.1.10", "192.168.1.10:8082" or a full URL. localOrigin still validates it. */
|
||||
fun typedAddress(value: String): String {
|
||||
val trimmed = value.trim().trimEnd('/')
|
||||
val scheme = if ("://" in trimmed) trimmed.substringBefore("://") else "http"
|
||||
val rest = trimmed.substringAfter("://")
|
||||
val authority = rest.substringBefore('/')
|
||||
val path = rest.removePrefix(authority)
|
||||
return "$scheme://$authority${if (':' in authority) "" else ":8082"}$path"
|
||||
}
|
||||
fun localOrigin(value: String): String? {
|
||||
val uri = Uri.parse(value)
|
||||
if (uri.scheme != "http" || uri.port != 8082 || uri.userInfo != null) return null
|
||||
val octets = uri.host?.split('.')?.map { it.toIntOrNull() ?: return null } ?: return null
|
||||
if (octets.size != 4 || octets.any { it !in 0..255 }) return null
|
||||
if (!(octets[0] == 10 || (octets[0] == 172 && octets[1] in 16..31) || (octets[0] == 192 && octets[1] == 168))) return null
|
||||
return "http://${octets.joinToString(".")}:8082"
|
||||
}
|
||||
}
|
||||
|
||||
class AndroidCellularTransport(private val network: Network) : CellularTransport {
|
||||
override fun resolve(host: String) = network.getAllByName(host)
|
||||
override fun socket() = network.socketFactory.createSocket()
|
||||
override fun datagram() = java.net.DatagramSocket(null).apply { network.bindSocket(this); bind(java.net.InetSocketAddress(0)) }
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.res.ColorStateList
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.ScrollView
|
||||
import android.widget.TextView
|
||||
|
||||
class PairingProgressDialog(activity: Activity, cancel: () -> Unit) {
|
||||
private val dialog = AlertDialog.Builder(activity, R.style.AppDialog)
|
||||
.setTitle("Pairing with comma")
|
||||
.setCancelable(false)
|
||||
.setNegativeButton("Cancel") { _, _ -> cancel() }
|
||||
.create()
|
||||
private val context = dialog.context
|
||||
private fun px(value: Int) = (value * context.resources.displayMetrics.density).toInt()
|
||||
private val stages = listOf("Check comma", "Open pairing window", "Connect over Bluetooth", "Pair Galaxy", "Set up music")
|
||||
private val labels = stages.map { TextView(context).apply { textSize = 14f; setPadding(0, px(5), 0, px(5)) } }
|
||||
private val detail = TextView(context).apply {
|
||||
textSize = 15f
|
||||
setTextColor(Palette.ON)
|
||||
accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
|
||||
}
|
||||
private var stage = 0
|
||||
|
||||
init {
|
||||
val content = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(px(24), px(8), px(24), px(16))
|
||||
labels.forEach { addView(it) }
|
||||
addView(LinearLayout(context).apply {
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
setPadding(0, px(16), 0, 0)
|
||||
addView(ProgressBar(context).apply {
|
||||
isIndeterminate = true
|
||||
indeterminateTintList = ColorStateList.valueOf(Palette.VIOLET)
|
||||
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
}, LinearLayout.LayoutParams(px(22), px(22)).apply { marginEnd = px(12) })
|
||||
addView(detail, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
|
||||
})
|
||||
}
|
||||
dialog.setView(ScrollView(context).apply { addView(content) })
|
||||
}
|
||||
|
||||
fun update(text: String, nextStage: Int? = null) {
|
||||
if (nextStage != null) stage = nextStage.coerceIn(stages.indices)
|
||||
labels.forEachIndexed { index, label ->
|
||||
label.text = "${if (index < stage) "✓" else "${index + 1}."} ${stages[index]}"
|
||||
label.setTextColor(when { index < stage -> Palette.CYAN; index == stage -> Palette.VIOLET_SOFT; else -> Palette.MUTED })
|
||||
}
|
||||
detail.text = text
|
||||
if (!dialog.isShowing) dialog.show()
|
||||
}
|
||||
|
||||
fun dismiss() = dialog.dismiss()
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import java.security.KeyStore
|
||||
import java.util.Base64
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class PairingStore(context: Context) {
|
||||
companion object { private val PHONE_ID = Regex("[0-9a-f]{8}") }
|
||||
private val prefs = context.getSharedPreferences("bluetooth-pairing", Context.MODE_PRIVATE)
|
||||
private fun key(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getKey("galaxy-pairing", null) as? SecretKey)?.let { return it }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run {
|
||||
init(KeyGenParameterSpec.Builder("galaxy-pairing", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
|
||||
generateKey()
|
||||
}
|
||||
}
|
||||
/** [id] is comma's id for this phone's key (newer comma). The id it replaces is kept so comma can drop that entry. */
|
||||
fun save(value: ByteArray, id: String? = null) {
|
||||
require(value.size == 32)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key())
|
||||
val previous = id()
|
||||
prefs.edit().remove("deviceAddress").remove("stale").remove("musicAddress").putString("key", Base64.getEncoder().encodeToString(cipher.iv + cipher.doFinal(value)))
|
||||
.apply { if (id != null && PHONE_ID.matches(id)) putString("id", id) else remove("id") }
|
||||
.apply { if (previous != null && previous != id) putString("previousId", previous) else remove("previousId") }
|
||||
.commit()
|
||||
}
|
||||
fun id(): String? = prefs.getString("id", null)?.takeIf { PHONE_ID.matches(it) }
|
||||
fun previousId(): String? = prefs.getString("previousId", null)?.takeIf { PHONE_ID.matches(it) }
|
||||
fun load(): ByteArray? = try {
|
||||
prefs.getString("key", null)?.let {
|
||||
val value = Base64.getDecoder().decode(it)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, value.copyOfRange(0, 12)))
|
||||
cipher.doFinal(value.copyOfRange(12, value.size)).also { decoded -> require(decoded.size == 32) }
|
||||
}
|
||||
} catch (_: Exception) { null }
|
||||
fun rememberDevice(address: String) {
|
||||
require(address.matches(Regex("(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){5}")))
|
||||
prefs.edit().putString("deviceAddress", address.uppercase()).apply()
|
||||
}
|
||||
fun deviceAddress(): String? = prefs.getString("deviceAddress", null)?.takeIf {
|
||||
it.matches(Regex("(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){5}"))
|
||||
}
|
||||
/** Comma's audio address once this phone bonded with it, so forgetting comma in Bluetooth settings can drop the app pairing too. */
|
||||
fun rememberMusic(address: String) {
|
||||
if (address.matches(Regex("(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){5}"))) prefs.edit().putString("musicAddress", address.uppercase()).apply()
|
||||
}
|
||||
fun musicAddress(): String? = prefs.getString("musicAddress", null)
|
||||
/** Comma stopped recognizing this key (forgotten there); the app stops reconnecting until it is paired again. */
|
||||
fun markStale() { prefs.edit().putBoolean("stale", true).apply() }
|
||||
fun stale(): Boolean = prefs.getBoolean("stale", false)
|
||||
fun forget() { prefs.edit().clear().commit() }
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
/** Phone fix sent to comma's `POST /api/companion/location`; comma uses it only when its own GPS has no fix. */
|
||||
object PhoneGps {
|
||||
const val PATH = "/api/companion/location"
|
||||
const val MAX_AGE_MS = 2000L
|
||||
|
||||
data class Fix(
|
||||
val latitude: Double, val longitude: Double, val accuracy: Float, val timestamp: Long,
|
||||
val altitude: Double? = null, val verticalAccuracy: Float? = null,
|
||||
val speed: Float? = null, val speedAccuracy: Float? = null,
|
||||
val bearing: Float? = null, val bearingAccuracy: Float? = null,
|
||||
)
|
||||
|
||||
/** Null when the fix is too old or has no usable position. Unknown values are left out. */
|
||||
fun payload(fix: Fix, ageMs: Long): Map<String, Any>? {
|
||||
if (ageMs !in 0..MAX_AGE_MS || !fix.latitude.isFinite() || !fix.longitude.isFinite() || !(fix.accuracy > 0f)) return null
|
||||
val values = linkedMapOf<String, Any>("latitude" to fix.latitude, "longitude" to fix.longitude,
|
||||
"horizontalAccuracy" to fix.accuracy.toDouble(), "ageMs" to ageMs, "timestamp" to fix.timestamp.coerceAtLeast(0))
|
||||
fun put(key: String, value: Number?) { value?.toDouble()?.takeIf { it.isFinite() && it >= 0 }?.let { values[key] = it } }
|
||||
fix.altitude?.takeIf { it.isFinite() }?.let { values["altitude"] = it }
|
||||
put("verticalAccuracy", fix.verticalAccuracy)
|
||||
put("speed", fix.speed)
|
||||
put("speedAccuracy", fix.speedAccuracy)
|
||||
if (fix.bearingAccuracy != null) { put("bearing", fix.bearing); put("bearingAccuracy", fix.bearingAccuracy) }
|
||||
return values
|
||||
}
|
||||
}
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.Manifest
|
||||
import android.app.*
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.Base64
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Sends this phone's GPS to comma about once a second, over Bluetooth or Galaxy Wi-Fi. */
|
||||
class PhoneGpsService : Service(), LocationListener {
|
||||
companion object {
|
||||
fun enabled(prefs: android.content.SharedPreferences) = prefs.getBoolean("phoneGps", false)
|
||||
}
|
||||
private val prefs by lazy { getSharedPreferences("companion", MODE_PRIVATE) }
|
||||
private val executor = Executors.newSingleThreadScheduledExecutor()
|
||||
@Volatile private var latest: Location? = null
|
||||
@Volatile private var stopped = false
|
||||
private var sent = 0L
|
||||
private var cookie = ""
|
||||
private var lastBluetoothAttempt = 0L
|
||||
private var own: BleTransport? = null
|
||||
private var status = ""
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
getSystemService(NotificationManager::class.java).createNotificationChannel(NotificationChannel("phone-gps", "Phone GPS", NotificationManager.IMPORTANCE_LOW))
|
||||
val first = notification("Waiting for GPS")
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 29) startForeground(2, first, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) else startForeground(2, first)
|
||||
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) throw SecurityException("Location permission")
|
||||
getSystemService(LocationManager::class.java).requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, this, Looper.getMainLooper())
|
||||
} catch (_: Exception) {
|
||||
// Android refuses location in the background after the permission is withdrawn.
|
||||
prefs.edit().putBoolean("phoneGps", false).apply(); stopped = true; stopSelf(); return
|
||||
}
|
||||
executor.scheduleWithFixedDelay({ tick() }, 1, 1, TimeUnit.SECONDS)
|
||||
}
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == "stop" || !enabled(prefs)) {
|
||||
prefs.edit().putBoolean("phoneGps", false).apply(); stopSelf(); return START_NOT_STICKY
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
override fun onLocationChanged(location: Location) { latest = location }
|
||||
@Deprecated("Required before Android 10") override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
|
||||
override fun onProviderEnabled(provider: String) {}
|
||||
override fun onProviderDisabled(provider: String) {}
|
||||
|
||||
private fun tick() {
|
||||
if (stopped) return
|
||||
val location = latest ?: return update("Waiting for GPS")
|
||||
if (location.elapsedRealtimeNanos == sent) return
|
||||
val age = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000
|
||||
val payload = PhoneGps.payload(PhoneGps.Fix(location.latitude, location.longitude, location.accuracy, location.time,
|
||||
location.altitude.takeIf { location.hasAltitude() }, location.verticalAccuracyMeters.takeIf { location.hasVerticalAccuracy() },
|
||||
location.speed.takeIf { location.hasSpeed() }, location.speedAccuracyMetersPerSecond.takeIf { location.hasSpeedAccuracy() },
|
||||
location.bearing.takeIf { location.hasBearing() }, location.bearingAccuracyDegrees.takeIf { location.hasBearingAccuracy() }), age)
|
||||
?: return update("Waiting for GPS")
|
||||
val body = JSONObject(payload).toString().toByteArray()
|
||||
try {
|
||||
send(body)
|
||||
sent = location.elapsedRealtimeNanos
|
||||
update("Sharing GPS with comma")
|
||||
} catch (_: Exception) { update("Waiting for comma") }
|
||||
}
|
||||
private fun send(body: ByteArray) {
|
||||
val ble = BleTransport.active?.takeIf { it.open } ?: Networks.wifi(this)?.let { wifi -> return post(wifi.first, body) } ?: bluetooth()
|
||||
?: throw IllegalStateException("comma unavailable")
|
||||
val response = ble.request(JSONObject().put("method", "POST").put("path", PhoneGps.PATH)
|
||||
.put("headers", JSONObject().put("content-type", "application/json")).put("body", Base64.getEncoder().encodeToString(body)))
|
||||
require(response.getInt("status") == 200)
|
||||
}
|
||||
/** Opens Bluetooth only when no other part of the app holds or is opening the connection. */
|
||||
private fun bluetooth(): BleTransport? {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (BleTransport.active != null || BleTransport.busy || now - lastBluetoothAttempt < 15_000) return null
|
||||
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return null
|
||||
lastBluetoothAttempt = now
|
||||
val pairing = PairingStore(this)
|
||||
val key = pairing.load() ?: return null
|
||||
val address = pairing.deviceAddress() ?: return null
|
||||
val transport = BleTransport(this, key)
|
||||
return try { transport.connect(address); own = transport; transport } catch (_: Exception) { transport.close(); null }
|
||||
}
|
||||
private fun post(network: android.net.Network, body: ByteArray) {
|
||||
for (attempt in 0..1) {
|
||||
if (cookie.isEmpty()) cookie = open(network, "/api/auth/session").run {
|
||||
try { getHeaderField("Set-Cookie")?.substringBefore(';') ?: "" } finally { disconnect() }
|
||||
}
|
||||
val connection = open(network, PhoneGps.PATH)
|
||||
try {
|
||||
connection.requestMethod = "POST"; connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.outputStream.use { it.write(body) }
|
||||
if (connection.responseCode == 200) return
|
||||
if (connection.responseCode != 401) error("Galaxy rejected the location")
|
||||
} finally { connection.disconnect() }
|
||||
cookie = ""
|
||||
}
|
||||
error("Galaxy session unavailable")
|
||||
}
|
||||
private fun open(network: android.net.Network, path: String) = (network.openConnection(URL(Networks.ORIGIN + path)) as HttpURLConnection).apply {
|
||||
connectTimeout = 2000; readTimeout = 2000; instanceFollowRedirects = false
|
||||
setRequestProperty("Origin", Networks.ORIGIN)
|
||||
if (cookie.isNotEmpty()) setRequestProperty("Cookie", cookie)
|
||||
}
|
||||
private fun notification(text: String): Notification {
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val stop = PendingIntent.getService(this, 1, Intent(this, PhoneGpsService::class.java).setAction("stop"), PendingIntent.FLAG_IMMUTABLE)
|
||||
return Notification.Builder(this, "phone-gps").setSmallIcon(android.R.drawable.ic_menu_mylocation)
|
||||
.setContentTitle("StarPilot phone GPS").setContentText(text).setContentIntent(open).setOngoing(true)
|
||||
.addAction(Notification.Action.Builder(null, "Stop", stop).build()).build()
|
||||
}
|
||||
private fun update(text: String) {
|
||||
if (stopped || text == status) return
|
||||
status = text
|
||||
getSystemService(NotificationManager::class.java).notify(2, notification(text))
|
||||
}
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
override fun onDestroy() {
|
||||
stopped = true
|
||||
executor.shutdownNow()
|
||||
getSystemService(LocationManager::class.java).removeUpdates(this)
|
||||
own?.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.*
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.TextView
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
class ShareActivity : Activity() {
|
||||
private val done = AtomicBoolean(false)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||
override fun onCreate(state: Bundle?) {
|
||||
super.onCreate(state)
|
||||
setContentView(TextView(this).apply { text = "Opening destination in Galaxy…"; setPadding(40, 100, 40, 40) })
|
||||
val text = (intent.getStringExtra(Intent.EXTRA_TEXT) ?: intent.dataString ?: "").take(8192)
|
||||
val short = Regex("https://(?:maps\\.app\\.goo\\.gl|goo\\.gl/maps)/[^\\s]+").find(text)?.value
|
||||
if (short == null) { complete(text); return }
|
||||
val cb = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
Thread {
|
||||
var result: String = short
|
||||
try {
|
||||
repeat(5) {
|
||||
val url = URL(result)
|
||||
require(url.protocol == "https" && (url.host == "maps.app.goo.gl" || url.host == "goo.gl" || url.host == "google.com" || url.host.endsWith(".google.com")))
|
||||
val connection = network.openConnection(url) as HttpURLConnection
|
||||
try {
|
||||
connection.instanceFollowRedirects = false; connection.connectTimeout = 1500; connection.readTimeout = 1500
|
||||
val code = connection.responseCode
|
||||
if (code in 300..399) {
|
||||
val next = connection.getHeaderField("Location") ?: return@repeat
|
||||
result = URL(url, next).toString()
|
||||
}
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
} catch (_: Exception) { }
|
||||
complete(result)
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
callback = cb
|
||||
Networks.manager(this).requestNetwork(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), cb)
|
||||
handler.postDelayed({ complete(text) }, 12000)
|
||||
}
|
||||
private fun complete(text: String) { runOnUiThread {
|
||||
if (!done.compareAndSet(false, true)) return@runOnUiThread
|
||||
startActivity(Intent(this, MainActivity::class.java).putExtra("share", text).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
|
||||
finish()
|
||||
} }
|
||||
override fun onDestroy() {
|
||||
done.set(true); handler.removeCallbacksAndMessages(null)
|
||||
callback?.let { Networks.manager(this).unregisterNetworkCallback(it) }
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
-180
@@ -1,180 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import java.io.Closeable
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
import java.net.*
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Semaphore
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
interface CellularTransport {
|
||||
fun resolve(host: String): Array<InetAddress>
|
||||
fun socket(): Socket
|
||||
fun datagram(): DatagramSocket
|
||||
}
|
||||
|
||||
/** RFC 1928 CONNECT + UDP ASSOCIATE and RFC 1929 authentication. No DNS on Wi-Fi. */
|
||||
class SocksServer(private val wifi: Inet4Address, private val cellular: CellularTransport,
|
||||
private val user: String, private val password: String, private val count: (Int) -> Unit, private val gateway: String = "172.31.254.1", listenPort: Int = 1080) : Closeable {
|
||||
private val open = AtomicBoolean(true)
|
||||
private val resources = ConcurrentHashMap.newKeySet<Closeable>()
|
||||
private val clients = Semaphore(24)
|
||||
private val pool = Executors.newCachedThreadPool()
|
||||
private val server = ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress(wifi, listenPort), 24) }
|
||||
val port: Int get() = server.localPort
|
||||
@Volatile var deniedHosts: Set<String> = setOf("commadataci.blob.core.windows.net", "commadata2.blob.core.windows.net", "upload.comma.ai", "logs.comma.ai")
|
||||
init {
|
||||
resources.add(server)
|
||||
pool.execute {
|
||||
while (open.get()) {
|
||||
val socket = try { server.accept() } catch (_: Exception) { break }
|
||||
// Only the comma gateway may use this listener, even with credentials.
|
||||
if (socket.inetAddress.hostAddress != gateway || !clients.tryAcquire()) { socket.close(); continue }
|
||||
resources.add(socket)
|
||||
pool.execute { try { serve(socket) } catch (_: Exception) { } finally { resources.remove(socket); socket.close(); clients.release() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun DataInputStream.string(): String {
|
||||
val length = readUnsignedByte()
|
||||
require(length > 0)
|
||||
return ByteArray(length).also { readFully(it) }.toString(Charsets.UTF_8)
|
||||
}
|
||||
private data class Target(val host: String, val port: Int)
|
||||
private fun target(input: DataInputStream): Target {
|
||||
val host = when (input.readUnsignedByte()) {
|
||||
1 -> InetAddress.getByAddress(ByteArray(4).also { input.readFully(it) }).hostAddress!!
|
||||
3 -> input.string()
|
||||
4 -> InetAddress.getByAddress(ByteArray(16).also { input.readFully(it) }).hostAddress!!
|
||||
else -> throw IllegalArgumentException("Unsupported address type")
|
||||
}
|
||||
return Target(host, input.readUnsignedShort())
|
||||
}
|
||||
private fun resolve(target: Target): InetAddress {
|
||||
val host = target.host.lowercase().trimEnd('.')
|
||||
require(target.port in 1..65535 && host.length <= 253)
|
||||
require(deniedHosts.none { host == it || host.endsWith(".$it") })
|
||||
return cellular.resolve(host).firstOrNull {
|
||||
!it.isAnyLocalAddress && !it.isLoopbackAddress && !it.isLinkLocalAddress && !it.isSiteLocalAddress && !it.isMulticastAddress &&
|
||||
!(it.address.size == 16 && (it.address[0].toInt() and 0xfe) == 0xfc)
|
||||
} ?: throw IllegalArgumentException("No public cellular address")
|
||||
}
|
||||
private fun reply(output: DataOutputStream, code: Int, address: InetAddress = wifi, port: Int = 0) {
|
||||
output.write(byteArrayOf(5, code.toByte(), 0, if (address.address.size == 4) 1 else 4))
|
||||
output.write(address.address); output.writeShort(port); output.flush()
|
||||
}
|
||||
private fun serve(client: Socket) {
|
||||
client.soTimeout = 10000
|
||||
val input = DataInputStream(client.getInputStream())
|
||||
val output = DataOutputStream(client.getOutputStream())
|
||||
require(input.readUnsignedByte() == 5)
|
||||
val methods = ByteArray(input.readUnsignedByte()).also { input.readFully(it) }
|
||||
output.write(byteArrayOf(5, if (methods.contains(2)) 2 else 0xff.toByte())); output.flush()
|
||||
if (!methods.contains(2)) return
|
||||
require(input.readUnsignedByte() == 1)
|
||||
val valid = input.string() == user && input.string() == password
|
||||
output.write(byteArrayOf(1, if (valid) 0 else 1)); output.flush()
|
||||
if (!valid) return
|
||||
require(input.readUnsignedByte() == 5)
|
||||
val command = input.readUnsignedByte()
|
||||
require(input.readUnsignedByte() == 0)
|
||||
val destination = target(input)
|
||||
when (command) {
|
||||
1 -> {
|
||||
val remote = cellular.socket()
|
||||
resources.add(remote)
|
||||
try {
|
||||
try { remote.connect(InetSocketAddress(resolve(destination), destination.port), 8000) }
|
||||
catch (_: Exception) { reply(output, 4); return }
|
||||
reply(output, 0)
|
||||
client.soTimeout = 120000; remote.soTimeout = 120000
|
||||
val upstream = pool.submit { pump(client, remote) }
|
||||
pump(remote, client)
|
||||
upstream.get(125, java.util.concurrent.TimeUnit.SECONDS)
|
||||
} finally { resources.remove(remote); remote.close() }
|
||||
}
|
||||
3 -> udp(client, input, output)
|
||||
else -> reply(output, 7)
|
||||
}
|
||||
}
|
||||
private fun pump(source: Socket, destination: Socket) {
|
||||
try {
|
||||
val buffer = ByteArray(32768)
|
||||
val input = source.getInputStream(); val output = destination.getOutputStream()
|
||||
while (open.get()) {
|
||||
val size = input.read(buffer)
|
||||
if (size < 0) break
|
||||
count(size); output.write(buffer, 0, size)
|
||||
}
|
||||
destination.shutdownOutput()
|
||||
} catch (_: Exception) { try { source.close(); destination.close() } catch (_: Exception) { } }
|
||||
}
|
||||
private fun udp(client: Socket, input: DataInputStream, output: DataOutputStream) {
|
||||
val local = DatagramSocket(InetSocketAddress(wifi, 0))
|
||||
resources.add(local)
|
||||
try {
|
||||
val outbound = cellular.datagram()
|
||||
resources.add(outbound)
|
||||
try { relayUdp(client, input, output, local, outbound) }
|
||||
finally { outbound.close(); resources.remove(outbound) }
|
||||
} finally { local.close(); resources.remove(local) }
|
||||
}
|
||||
private fun relayUdp(client: Socket, input: DataInputStream, output: DataOutputStream,
|
||||
local: DatagramSocket, outbound: DatagramSocket) {
|
||||
val association = AtomicBoolean(true)
|
||||
val allowed = ConcurrentHashMap.newKeySet<InetSocketAddress>()
|
||||
var peer: InetSocketAddress? = null
|
||||
val peerLock = Any()
|
||||
reply(output, 0, wifi, local.localPort)
|
||||
val sender = pool.submit {
|
||||
val buffer = ByteArray(65535)
|
||||
while (association.get() && open.get()) {
|
||||
try {
|
||||
val packet = DatagramPacket(buffer, buffer.size); local.receive(packet)
|
||||
if (packet.address != client.inetAddress) continue
|
||||
val senderAddress = InetSocketAddress(packet.address, packet.port)
|
||||
synchronized(peerLock) { if (peer == null) peer = senderAddress }
|
||||
if (synchronized(peerLock) { peer } != senderAddress) continue
|
||||
val bytes = DataInputStream(packet.data.inputStream(0, packet.length))
|
||||
if (bytes.readUnsignedShort() != 0 || bytes.readUnsignedByte() != 0) continue // No fragments.
|
||||
val destination = target(bytes)
|
||||
val remote = InetSocketAddress(resolve(destination), destination.port)
|
||||
if (allowed.size >= 128 && !allowed.contains(remote)) continue
|
||||
allowed.add(remote)
|
||||
val payload = bytes.readBytes()
|
||||
outbound.send(DatagramPacket(payload, payload.size, remote)); count(payload.size)
|
||||
} catch (_: Exception) { if (local.isClosed || outbound.isClosed) break }
|
||||
}
|
||||
}
|
||||
val receiver = pool.submit {
|
||||
val buffer = ByteArray(65535)
|
||||
while (association.get() && open.get()) {
|
||||
try {
|
||||
val packet = DatagramPacket(buffer, buffer.size); outbound.receive(packet)
|
||||
if (!allowed.contains(InetSocketAddress(packet.address, packet.port))) continue
|
||||
val receiverAddress = synchronized(peerLock) { peer } ?: continue
|
||||
val framed = java.io.ByteArrayOutputStream()
|
||||
val header = DataOutputStream(framed)
|
||||
header.writeShort(0); header.writeByte(0); header.writeByte(if (packet.address.address.size == 4) 1 else 4)
|
||||
header.write(packet.address.address); header.writeShort(packet.port); header.write(packet.data, 0, packet.length)
|
||||
val data = framed.toByteArray()
|
||||
local.send(DatagramPacket(data, data.size, receiverAddress)); count(packet.length)
|
||||
} catch (_: Exception) { if (local.isClosed || outbound.isClosed) break }
|
||||
}
|
||||
}
|
||||
try {
|
||||
client.soTimeout = 0
|
||||
while (open.get() && input.read() != -1) { /* TCP connection owns UDP association. */ }
|
||||
} finally {
|
||||
association.set(false); local.close(); outbound.close(); sender.cancel(true); receiver.cancel(true)
|
||||
resources.remove(local); resources.remove(outbound)
|
||||
}
|
||||
}
|
||||
override fun close() {
|
||||
open.set(false)
|
||||
resources.forEach { try { it.close() } catch (_: Exception) { } }
|
||||
pool.shutdownNow()
|
||||
}
|
||||
}
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import android.app.*
|
||||
import android.content.Intent
|
||||
import android.net.*
|
||||
import android.os.IBinder
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.SecureRandom
|
||||
import java.time.LocalDate
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class UplinkService : Service() {
|
||||
private val prefs by lazy { getSharedPreferences("companion", MODE_PRIVATE) }
|
||||
private val executor = Executors.newSingleThreadScheduledExecutor()
|
||||
@Volatile private var cellular: Network? = null
|
||||
private val sessionLock = Any()
|
||||
@Volatile private var stopped = false
|
||||
@Volatile private var socks: SocksServer? = null
|
||||
private var identity: String? = null
|
||||
private var cookie = ""
|
||||
private var bytes = 0L
|
||||
private var day = ""
|
||||
private val counterLock = Any()
|
||||
private var username = ""
|
||||
private var password = ""
|
||||
private val callback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) { cellular = network }
|
||||
override fun onLost(network: Network) { if (cellular == network) cellular = null }
|
||||
}
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
getSystemService(NotificationManager::class.java).createNotificationChannel(NotificationChannel("uplink", "Phone internet", NotificationManager.IMPORTANCE_LOW))
|
||||
startForeground(1, notification("Waiting for Galaxy Wi-Fi and mobile data"))
|
||||
bytes = prefs.getLong("bytes", 0); day = prefs.getString("day", "")!!
|
||||
Networks.manager(this).requestNetwork(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), callback)
|
||||
executor.scheduleWithFixedDelay({ tick() }, 0, 5, TimeUnit.SECONDS)
|
||||
}
|
||||
private fun notification(text: String): Notification {
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val stop = PendingIntent.getService(this, 1, Intent(this, UplinkService::class.java).setAction("stop"), PendingIntent.FLAG_IMMUTABLE)
|
||||
return Notification.Builder(this, "uplink").setSmallIcon(android.R.drawable.stat_sys_upload)
|
||||
.setContentTitle("StarPilot phone internet").setContentText(text).setContentIntent(open).setOngoing(true)
|
||||
.addAction(Notification.Action.Builder(null, "Stop", stop).build()).build()
|
||||
}
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == "stop" || !prefs.getBoolean("enabled", false)) {
|
||||
prefs.edit().putBoolean("enabled", false).apply(); stopSelf(); return START_NOT_STICKY
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
private fun reset() { synchronized(sessionLock) { socks?.close(); socks = null; identity = null; cookie = "" } }
|
||||
private fun secret(): String = ByteArray(24).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
private fun count(size: Int) { synchronized(counterLock) {
|
||||
val today = LocalDate.now().toString()
|
||||
if (day != today) { day = today; bytes = 0 }
|
||||
bytes += size
|
||||
} }
|
||||
private fun request(network: Network, path: String, body: JSONObject? = null): JSONObject {
|
||||
val connection = network.openConnection(URL(Networks.ORIGIN + path)) as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 2000; connection.readTimeout = 2000; connection.instanceFollowRedirects = false
|
||||
connection.setRequestProperty("Origin", Networks.ORIGIN)
|
||||
if (cookie.isNotEmpty()) connection.setRequestProperty("Cookie", cookie)
|
||||
if (body != null) {
|
||||
connection.requestMethod = "POST"; connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.outputStream.use { it.write(body.toString().toByteArray()) }
|
||||
}
|
||||
require(connection.responseCode == 200) { "Galaxy unavailable" }
|
||||
connection.getHeaderField("Set-Cookie")?.let { cookie = it.substringBefore(';') }
|
||||
return JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
private fun tick() {
|
||||
try {
|
||||
if (stopped || !prefs.getBoolean("enabled", false)) { reset(); return }
|
||||
val wifi = Networks.wifi(this)
|
||||
val cell = cellular
|
||||
if (wifi == null || cell == null || Networks.manager(this).getNetworkCapabilities(cell)?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) != true) { reset(); update("Waiting for Galaxy Wi-Fi and mobile data"); return }
|
||||
val current = "${wifi.first}:${wifi.second.hostAddress}:$cell"
|
||||
synchronized(sessionLock) {
|
||||
if (stopped) return
|
||||
if (identity != current) {
|
||||
reset(); username = secret(); password = secret()
|
||||
socks = SocksServer(wifi.second, AndroidCellularTransport(cell), username, password, ::count); identity = current
|
||||
}
|
||||
}
|
||||
// Refresh the short-lived LAN session every heartbeat, independent of WebView cookies.
|
||||
request(wifi.first, "/api/auth/session")
|
||||
val used = synchronized(counterLock) {
|
||||
count(0)
|
||||
prefs.edit().putLong("bytes", bytes).putString("day", day).apply()
|
||||
bytes
|
||||
}
|
||||
val response = request(wifi.first, "/api/companion/uplink", JSONObject().put("port", 1080).put("user", username)
|
||||
.put("pass", password).put("protocol", Networks.PROTOCOL).put("version", BuildConfig.VERSION_NAME).put("bytes", used))
|
||||
val deny = response.getJSONArray("uploadDenyHosts")
|
||||
socks?.deniedHosts = (0 until deny.length()).map { deny.getString(it).lowercase() }.toSet()
|
||||
if (!response.getBoolean("enabled")) { reset(); update("Enable phone internet in Galaxy"); return }
|
||||
update((if (response.optBoolean("active")) "Sharing mobile data with comma" else "Phone internet ready") + " · %.1f MB today".format(used / 1048576.0))
|
||||
} catch (_: Exception) {
|
||||
// Keep the SOCKS listener and credentials: the comma still routes to them until its lease expires.
|
||||
synchronized(sessionLock) { cookie = "" }
|
||||
update("Reconnecting to Galaxy…")
|
||||
}
|
||||
}
|
||||
private fun update(text: String) { if (stopped) return; getSystemService(NotificationManager::class.java).notify(1, notification(text)) }
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
override fun onDestroy() {
|
||||
stopped = true
|
||||
executor.shutdownNow()
|
||||
Networks.manager(this).unregisterNetworkCallback(callback)
|
||||
reset()
|
||||
synchronized(counterLock) { prefs.edit().putLong("bytes", bytes).putString("day", day).apply() }
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
<inset xmlns:android="http://schemas.android.com/apk/res/android" android:inset="16dp">
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="24dp" />
|
||||
<solid android:color="#110E1F" />
|
||||
<stroke android:width="1dp" android:color="#1FFFFFFF" />
|
||||
</shape>
|
||||
</inset>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.8 KiB |
@@ -1,7 +0,0 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<group android:pivotX="12" android:pivotY="12" android:rotation="-20">
|
||||
<path android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:fillColor="#00000000" android:pathData="M1.5,12a10.5,4.6 0 1,0 21,0a10.5,4.6 0 1,0 -21,0" />
|
||||
</group>
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M8.6,12a3.4,3.4 0 1,0 6.8,0a3.4,3.4 0 1,0 -6.8,0" />
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M18.3,6.4a1.7,1.7 0 1,0 3.4,0a1.7,1.7 0 1,0 -3.4,0" />
|
||||
</vector>
|
||||
@@ -1,3 +0,0 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M17.71,7.71L12,2h-1v7.59L6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 11,14.41V22h1l5.71,-5.71 -4.3,-4.29 4.3,-4.29zM13,5.83l1.88,1.88L13,9.59V5.83zM14.88,16.29L13,18.17v-3.76l1.88,1.88z" />
|
||||
</vector>
|
||||
@@ -1,3 +0,0 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M13,22h8v-7h-3v-4h-5V9h3V2H8v7h3v2H6v4H3v7h8v-7H8v-2h8v2h-3V22z" />
|
||||
</vector>
|
||||
@@ -1,3 +0,0 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M1,9l2,2c4.97,-4.97 13.03,-4.97 18,0l2,-2C16.93,2.93 7.08,2.93 1,9zM9,17l3,3 3,-3c-1.65,-1.66 -4.34,-1.66 -6,0zM5,13l2,2c2.76,-2.76 7.24,-2.76 10,0l2,-2C15.14,9.14 8.87,9.14 5,13z" />
|
||||
</vector>
|
||||
-1
@@ -1 +0,0 @@
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"><background android:drawable="@android:color/black" /><foreground android:drawable="@drawable/galaxy" /></adaptive-icon>
|
||||
@@ -1,16 +0,0 @@
|
||||
<resources>
|
||||
<style name="AppTheme" parent="android:style/Theme.Material.NoActionBar">
|
||||
<item name="android:fontFamily">sans</item><item name="android:colorAccent">#9d72ff</item>
|
||||
<item name="android:windowLightStatusBar">false</item><item name="android:windowBackground">#070712</item>
|
||||
<item name="android:navigationBarColor">#070712</item><item name="android:statusBarColor">#070712</item>
|
||||
<item name="android:alertDialogTheme">@style/AppDialog</item>
|
||||
</style>
|
||||
<!-- Galaxy surface instead of the stock grey Material dialog. -->
|
||||
<style name="AppDialog" parent="android:style/Theme.Material.Dialog.Alert">
|
||||
<item name="android:windowBackground">@drawable/dialog_surface</item>
|
||||
<item name="android:colorBackground">#110E1F</item><item name="android:colorAccent">#9d72ff</item>
|
||||
<item name="android:textColorPrimary">#F3F2F8</item><item name="android:textColorSecondary">#9D9BB8</item>
|
||||
<item name="android:textColorHint">#8C9D9BB8</item><item name="android:colorControlNormal">#9D9BB8</item>
|
||||
<item name="android:colorControlActivated">#9d72ff</item><item name="android:colorControlHighlight">#3C9D72FF</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,5 +0,0 @@
|
||||
<network-security-config>
|
||||
<!-- Android has no CIDR matcher. MainActivity enforces numeric RFC1918 origins
|
||||
and intercepts every WebView request; the service uses only the fixed AP. -->
|
||||
<base-config cleartextTrafficPermitted="true" />
|
||||
</network-security-config>
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
class AppInstallPolicyTest {
|
||||
@Test fun acceptsOnlyBoundedApkResponses() {
|
||||
assertTrue(AppInstallPolicy.accepts(200, "application/vnd.android.package-archive", 1024))
|
||||
assertTrue(AppInstallPolicy.accepts(200, "application/vnd.android.package-archive; charset=binary", 1024))
|
||||
assertFalse(AppInstallPolicy.accepts(302, "application/vnd.android.package-archive", 1024))
|
||||
assertFalse(AppInstallPolicy.accepts(200, "text/html", 1024))
|
||||
assertFalse(AppInstallPolicy.accepts(200, "application/vnd.android.package-archive", 0))
|
||||
assertFalse(AppInstallPolicy.accepts(200, "application/vnd.android.package-archive", AppInstallPolicy.MAX_APK_BYTES + 1))
|
||||
}
|
||||
|
||||
@Test fun copiesExactlyTheAdvertisedLength() {
|
||||
val data = ByteArray(150000) { (it % 251).toByte() }
|
||||
val output = ByteArrayOutputStream()
|
||||
AppInstallPolicy.copyExact(ByteArrayInputStream(data), output, data.size.toLong())
|
||||
assertArrayEquals(data, output.toByteArray())
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
AppInstallPolicy.copyExact(ByteArrayInputStream(data), ByteArrayOutputStream(), data.size.toLong() - 1)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
AppInstallPolicy.copyExact(ByteArrayInputStream(data), ByteArrayOutputStream(), data.size.toLong() + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class AppUpdatePolicyTest {
|
||||
@Test fun android12DoesNotRequireRuntimeNotificationPermission() {
|
||||
assertTrue(AppUpdatePolicy.notificationsAllowed(31, true, true, false))
|
||||
assertTrue(AppUpdatePolicy.notificationsAllowed(32, true, true, false))
|
||||
assertFalse(AppUpdatePolicy.notificationsAllowed(33, true, true, false))
|
||||
assertTrue(AppUpdatePolicy.notificationsAllowed(33, true, true, true))
|
||||
assertFalse(AppUpdatePolicy.notificationsAllowed(31, false, true, true))
|
||||
assertFalse(AppUpdatePolicy.notificationsAllowed(31, true, false, true))
|
||||
}
|
||||
|
||||
@Test fun comparesNumericVersionsAndRejectsDowngrades() {
|
||||
assertTrue(AppUpdatePolicy.newerVersion("1.1.10", "1.1.9"))
|
||||
assertTrue(AppUpdatePolicy.newerVersion("1.2", "1.1.99"))
|
||||
for ((available, installed) in listOf("1.1.7" to "1.1.7", "1.1.6" to "1.1.7", "1.1" to "1.1.0",
|
||||
"" to "1.1.7", "unknown" to "1.1.7", "1.1.8" to "", "1.1.8-beta" to "1.1.7",
|
||||
"99999999999999999999999.0" to "1.1.7")) {
|
||||
assertFalse("$available vs $installed", AppUpdatePolicy.newerVersion(available, installed))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun alertsOncePerNewAvailableApkAndRequiresPermission() {
|
||||
assertTrue(AppUpdatePolicy.shouldNotify("1.1.8", "1.1.7", true, true, ""))
|
||||
assertFalse(AppUpdatePolicy.shouldNotify("1.1.8", "1.1.7", true, true, "1.1.8"))
|
||||
assertTrue(AppUpdatePolicy.shouldNotify("1.1.9", "1.1.7", true, true, "1.1.8"))
|
||||
assertFalse(AppUpdatePolicy.shouldNotify("1.1.8", "1.1.7", false, true, ""))
|
||||
assertFalse(AppUpdatePolicy.shouldNotify("1.1.8", "1.1.7", true, false, ""))
|
||||
assertFalse(AppUpdatePolicy.shouldNotify("1.1.7", "1.1.8", true, true, ""))
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class BleWireTest {
|
||||
private val key = ByteArray(32) { it.toByte() }
|
||||
private fun fixture(name: String) = javaClass.getResource("/ble/$name")!!.readText().trim()
|
||||
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
@Test fun pythonResponsesDecodeAndFragmentsReassemble() {
|
||||
for (name in listOf("plain", "compressed", "compact")) {
|
||||
val frame = hex(fixture("$name.hex"))
|
||||
for (size in listOf(20, 180, 512)) {
|
||||
val assembler = BleWire.Assembler()
|
||||
var result: ByteArray? = null
|
||||
for (packet in BleWire.packets(frame, size)) result = assembler.add(packet)
|
||||
val decoded = BleWire.decode(result!!, key)
|
||||
if (name == "compact") {
|
||||
assertArrayEquals(ByteArray(16384) { (it % 256).toByte() }, decoded.body)
|
||||
assertEquals("{\"id\":\"abc\",\"status\":200}", String(decoded.json))
|
||||
} else assertEquals(fixture("$name.json"), String(decoded.json))
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test fun androidRequestMatchesPythonVector() {
|
||||
val actual = BleWire.seal("{\"method\":\"GET\",\"path\":\"/api/companion/status\"}".toByteArray(), key,
|
||||
nonce = ByteArray(12) { it.toByte() })
|
||||
assertArrayEquals(hex(fixture("request.hex")), actual)
|
||||
}
|
||||
@Test fun tamperingWrongDirectionAndOutOfOrderFail() {
|
||||
val frame = hex(fixture("plain.hex"))
|
||||
val encrypted = frame.copyOfRange(4, frame.size)
|
||||
assertThrows(Exception::class.java) { BleWire.open(encrypted, key, "request") }
|
||||
encrypted[15] = (encrypted[15].toInt() xor 1).toByte()
|
||||
assertThrows(Exception::class.java) { BleWire.open(encrypted, key) }
|
||||
assertThrows(IllegalArgumentException::class.java) { BleWire.Assembler().add(BleWire.packets(frame, 20)[1]) }
|
||||
}
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import java.math.BigInteger
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
/** The vector comes from comma's own claim.py (see galaxy_bluetooth/tests), so both sides agree byte for byte. */
|
||||
class ClaimPairingTest {
|
||||
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
private val phone = ClaimPairing.privateKey(BigInteger("11".repeat(32), 16))
|
||||
private val challenge = ByteArray(16) { it.toByte() }
|
||||
private val phonePoint = hex("040217e617f0b6443928278f96999e69a23a4f2c152bdf6d6cdf66e5b80282d4ed194a7debcb97712d2dda3ca85aa8765a56f45fc758599652f2897c65306e5794")
|
||||
private val reply = hex("4743523104d65a93977caa3d1b081852ff57a79e465f1660577304baead505dd3a48589cf350185e895372df6221ea3a137557e473fddb6755f05bd507c3c533fce9c912856465666768696a6b6c6d6e6f56e085dc7bc3807c9c7cb045c4c1f175f83b778465883907450039ebf7bae2c056f9ce9975cfb418ec470cffe65a07209b6b0194c4f7858fdac068c0fb2f699f06cc4bfb9a8c6734d68a910c8d5329eadf05462b6c59013892e0522f5056974e80082afbb204b6cde770c4d5ed383ffe6f08909da1a7b716088c91d507bd197a3c8f48e8a53deaa7008f209ac1c78f733f078cd862345f0e2fab00241494bc7bc4be2a4769")
|
||||
|
||||
@Test fun opensCommasReply() {
|
||||
val claim = ClaimPairing.open(reply, phone, challenge)
|
||||
assertEquals("ab".repeat(32), claim.key.joinToString("") { "%02x".format(it) })
|
||||
assertEquals("0a1b2c3d", claim.id)
|
||||
assertEquals("AA:BB:CC:DD:EE:FF", claim.adapterAddress)
|
||||
assertEquals("comma", claim.adapterName)
|
||||
}
|
||||
|
||||
@Test fun readsEscapedAndMissingFields() {
|
||||
val json = """{"key":"${"cd".repeat(32)}","id":"0a1b2c3d","adapterAddress":"junk","adapterName":"Danny\u2019s \"comma\""}"""
|
||||
val claim = ClaimPairing.parse(json)
|
||||
assertEquals("Danny\u2019s \"comma\"", claim.adapterName)
|
||||
assertEquals("", claim.adapterAddress)
|
||||
assertThrows(IllegalArgumentException::class.java) { ClaimPairing.parse("""{"id":"0a1b2c3d"}""") }
|
||||
assertThrows(IllegalArgumentException::class.java) { ClaimPairing.parse("""{"key":"short"}""") }
|
||||
assertEquals("", ClaimPairing.parse("""{"key":"${"cd".repeat(32)}","id":"BAD"}""").id)
|
||||
}
|
||||
|
||||
@Test fun derivesTheSameKeyAsComma() {
|
||||
val server = reply.copyOfRange(4, 69)
|
||||
assertArrayEquals(hex("3b5c0f6357da2c229949fb3695c3656c009af9b8fa4a7588ce991292c6eb73e0"), ClaimPairing.derive(phone, server, challenge))
|
||||
}
|
||||
|
||||
@Test fun aWrongChallengeOrTamperedReplyIsRefused() {
|
||||
assertThrows(Exception::class.java) { ClaimPairing.open(reply, phone, ByteArray(16)) }
|
||||
assertThrows(Exception::class.java) { ClaimPairing.open(reply.copyOf().also { it[it.size - 1] = (it[it.size - 1].toInt() xor 1).toByte() }, phone, challenge) }
|
||||
assertThrows(Exception::class.java) { ClaimPairing.open(reply.copyOf().also { it[0] = 'X'.code.toByte() }, phone, challenge) }
|
||||
assertThrows(Exception::class.java) { ClaimPairing.open(reply.copyOfRange(0, 60), phone, challenge) }
|
||||
}
|
||||
|
||||
@Test fun aReplyForAnotherPhoneIsRefused() {
|
||||
val other = ClaimPairing.newKeyPair()
|
||||
assertThrows(Exception::class.java) { ClaimPairing.open(reply, other.private, challenge) }
|
||||
}
|
||||
|
||||
@Test fun requestsAreMagicPointAndName() {
|
||||
val pair = ClaimPairing.newKeyPair()
|
||||
val point = ClaimPairing.point(pair.public as ECPublicKey)
|
||||
assertEquals(65, point.size)
|
||||
assertEquals(4, point[0].toInt())
|
||||
val request = ClaimPairing.request(point, "Danny's Pixel 8")
|
||||
assertEquals("GCL1", String(request, 0, 4))
|
||||
assertArrayEquals(point, request.copyOfRange(4, 69))
|
||||
assertEquals("Danny's Pixel 8", String(request, 69, request.size - 69))
|
||||
assertEquals(40, ClaimPairing.request(point, "x".repeat(100)).size - 69)
|
||||
assertThrows(IllegalArgumentException::class.java) { ClaimPairing.request(ByteArray(65), "x") }
|
||||
}
|
||||
|
||||
@Test fun publicPointsRoundTripThroughDerive() {
|
||||
val a = ClaimPairing.newKeyPair()
|
||||
val b = ClaimPairing.newKeyPair()
|
||||
val aPoint = ClaimPairing.point(a.public as ECPublicKey)
|
||||
val bPoint = ClaimPairing.point(b.public as ECPublicKey)
|
||||
assertArrayEquals(ClaimPairing.derive(a.private, bPoint, challenge), ClaimPairing.derive(b.private, aPoint, challenge))
|
||||
assertEquals(phonePoint.size, aPoint.size)
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CommaBondTest {
|
||||
private val comma = "39:90:21:64:07:00"
|
||||
|
||||
@Test fun forgettingCommaInBluetoothSettingsEndsTheAppPairing() {
|
||||
assertTrue(CommaBond.forgotten(comma, "39:90:21:64:07:00", CommaBond.BOND_NONE))
|
||||
assertTrue(CommaBond.forgotten(comma, "39:90:21:64:07:00".lowercase(), CommaBond.BOND_NONE))
|
||||
}
|
||||
|
||||
@Test fun otherDevicesAndOtherBondStatesAreIgnored() {
|
||||
assertFalse(CommaBond.forgotten(comma, "AA:BB:CC:DD:EE:FF", CommaBond.BOND_NONE))
|
||||
assertFalse(CommaBond.forgotten(comma, comma, 11))
|
||||
assertFalse(CommaBond.forgotten(comma, comma, 12))
|
||||
assertFalse(CommaBond.forgotten(null, comma, CommaBond.BOND_NONE))
|
||||
assertFalse(CommaBond.forgotten(comma, null, CommaBond.BOND_NONE))
|
||||
}
|
||||
|
||||
@Test fun aBondMissingAtStartupMeansItWasForgottenWhileClosed() {
|
||||
assertTrue(CommaBond.missing(comma, setOf("AA:BB:CC:DD:EE:FF")))
|
||||
assertFalse(CommaBond.missing(comma, setOf("39:90:21:64:07:00")))
|
||||
assertFalse(CommaBond.missing(comma, setOf("39:90:21:64:07:00".lowercase())))
|
||||
assertFalse(CommaBond.missing(null, emptySet()))
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ConnectionRecoveryTest {
|
||||
@Test fun interruptedSearchResumesOnceAfterWifiSettings() {
|
||||
val events = mutableListOf<String>()
|
||||
val recovery = ConnectionRecovery({ events.add("search:$it") }, { events.add("connect") }, { events.add("stop") })
|
||||
recovery.resumed() // Initial onResume after onCreate must not duplicate its connection attempt.
|
||||
assertTrue(events.isEmpty())
|
||||
recovery.stopped(searchAutomatic = true, disconnected = true)
|
||||
assertEquals(listOf("stop"), events)
|
||||
recovery.resumed()
|
||||
recovery.resumed()
|
||||
assertEquals(listOf("stop", "search:true"), events)
|
||||
}
|
||||
|
||||
@Test fun disconnectedScreenReconnectsAfterJoiningWifi() {
|
||||
val events = mutableListOf<String>()
|
||||
val recovery = ConnectionRecovery({ events.add("search:$it") }, { events.add("connect") }, { events.add("stop") })
|
||||
recovery.stopped(searchAutomatic = null, disconnected = true)
|
||||
recovery.resumed()
|
||||
assertEquals(listOf("stop", "connect"), events)
|
||||
}
|
||||
|
||||
@Test fun manualSearchRetainsItsModeAndConnectedScreenStaysConnected() {
|
||||
val events = mutableListOf<String>()
|
||||
val recovery = ConnectionRecovery({ events.add("search:$it") }, { events.add("connect") }, { events.add("stop") })
|
||||
recovery.stopped(searchAutomatic = false, disconnected = false)
|
||||
recovery.resumed()
|
||||
assertEquals(listOf("stop", "search:false"), events)
|
||||
events.clear()
|
||||
recovery.stopped(searchAutomatic = null, disconnected = false)
|
||||
recovery.resumed()
|
||||
assertEquals(listOf("stop"), events)
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
|
||||
class GalaxyAssetsTest {
|
||||
private val root: File = Files.createTempDirectory("galaxy-assets").toFile()
|
||||
private val cache = File(root, "cache")
|
||||
private val prefs = object : GalaxyPrefs {
|
||||
val values = mutableMapOf<String, String>()
|
||||
override fun get(key: String) = values[key]
|
||||
override fun set(key: String, value: String) { values[key] = value }
|
||||
}
|
||||
private val files = mutableMapOf(
|
||||
"index.html" to "<html>Galaxy</html>", "js/boot.js" to "import './app.js'", "js/app.js" to "const galaxy = true",
|
||||
"data/catalog.json" to "{}", "sentry-push-worker.js" to "self.addEventListener('push', () => {})",
|
||||
).mapValues { it.value.toByteArray() }.toMutableMap()
|
||||
|
||||
private inner class Source(var commit: String? = "a".repeat(40)) : GalaxySource {
|
||||
var fileCalls = 0
|
||||
var corrupt = false
|
||||
var offline = false
|
||||
var tooOld = false
|
||||
override fun manifest(): GalaxySource.Listing {
|
||||
if (offline) throw IOException("offline")
|
||||
if (tooOld) throw GalaxyTooOldException()
|
||||
return GalaxySource.Listing(commit, files.map { (path, data) -> GalaxyAssetFile(path, GalaxyAssetManifest.sha256(data), data.size) })
|
||||
}
|
||||
override fun file(path: String, limit: Int): ByteArray { synchronized(this) { fileCalls++ }; return if (corrupt) "wrong".toByteArray() else files.getValue(path) }
|
||||
}
|
||||
|
||||
private fun store() = GalaxyAssetStore(cache, prefs)
|
||||
|
||||
@After fun cleanup() { root.deleteRecursively() }
|
||||
|
||||
@Test fun downloadsVerifiesAndSavesPagesFromComma() {
|
||||
val store = store(); val source = Source()
|
||||
assertNull(store.readyRoot)
|
||||
assertEquals(GalaxyAssetStore.NOT_DOWNLOADED, store.status)
|
||||
store.check(source)
|
||||
val ready = store.readyRoot!!
|
||||
assertEquals("const galaxy = true", File(ready, "js/app.js").readText())
|
||||
assertEquals(5, source.fileCalls)
|
||||
assertTrue(GalaxyAssetStore.verify(ready))
|
||||
assertEquals(ready, store().readyRoot)
|
||||
}
|
||||
|
||||
@Test fun refreshesWhenFilesChangeEvenIfTheCommitDoesNot() {
|
||||
val store = store(); val source = Source()
|
||||
store.check(source)
|
||||
store.check(source)
|
||||
assertEquals("Galaxy matches comma.", store.status)
|
||||
assertEquals(5, source.fileCalls)
|
||||
files["js/app.js"] = "const galaxy = 2".toByteArray()
|
||||
store.check(source)
|
||||
assertEquals(6, source.fileCalls)
|
||||
assertEquals("const galaxy = 2", File(store.readyRoot!!, "js/app.js").readText())
|
||||
}
|
||||
|
||||
@Test fun customOrUnpushedBuildsWorkBecauseNothingComesFromGitHub() {
|
||||
val source = Source(commit = null)
|
||||
files["js/custom-branch-only.js"] = "export default 1".toByteArray()
|
||||
val store = store()
|
||||
store.check(source)
|
||||
assertEquals("export default 1", File(store.readyRoot!!, "js/custom-branch-only.js").readText())
|
||||
assertFalse(store.olderThan("f".repeat(40)))
|
||||
}
|
||||
|
||||
@Test fun failuresKeepPreviousCopy() {
|
||||
val store = store(); val source = Source()
|
||||
store.check(source)
|
||||
val previous = store.readyRoot
|
||||
files["js/app.js"] = "changed".toByteArray(); source.corrupt = true
|
||||
store.check(source)
|
||||
assertEquals(previous, store.readyRoot)
|
||||
assertTrue(store.status.contains("verification failed"))
|
||||
source.corrupt = false; source.offline = true
|
||||
store.check(source)
|
||||
assertTrue(store.status.contains("reach comma"))
|
||||
source.offline = false; source.tooOld = true
|
||||
store.check(source)
|
||||
assertTrue(store.status.startsWith("Comma’s software is too old"))
|
||||
assertEquals(previous, store.readyRoot)
|
||||
assertEquals(listOf(previous!!.name), cache.list()!!.toList())
|
||||
}
|
||||
|
||||
@Test fun nothingSavedMeansNothingToServe() {
|
||||
val store = store(); val source = Source().apply { corrupt = true }
|
||||
store.check(source)
|
||||
assertNull(store.readyRoot)
|
||||
assertTrue(store.status.endsWith("No Galaxy screens are saved yet."))
|
||||
assertEquals(emptyList<String>(), cache.list()?.toList() ?: emptyList<String>())
|
||||
}
|
||||
|
||||
@Test fun noticesWhenCommaMovedOnSinceTheLastDownload() {
|
||||
val store = store()
|
||||
assertFalse(store.olderThan("b".repeat(40)))
|
||||
store.check(Source(commit = "a".repeat(40)))
|
||||
assertFalse(store.olderThan("a".repeat(40)))
|
||||
assertFalse(store.olderThan(null))
|
||||
assertTrue(store.olderThan("b".repeat(40)))
|
||||
}
|
||||
|
||||
@Test fun aFailedDownloadStillLeavesTheSavedScreensOlderThanComma() {
|
||||
val store = store()
|
||||
store.check(Source(commit = "a".repeat(40)))
|
||||
files["js/app.js"] = "changed".toByteArray()
|
||||
store.check(Source(commit = "b".repeat(40)).apply { corrupt = true })
|
||||
assertTrue(store.olderThan("b".repeat(40)))
|
||||
store.check(Source(commit = "b".repeat(40)))
|
||||
assertFalse(store.olderThan("b".repeat(40)))
|
||||
}
|
||||
|
||||
@Test fun tamperedSavedCopyIsNotTrusted() {
|
||||
store().check(Source())
|
||||
File(store().readyRoot!!, "js/app.js").writeText("tampered")
|
||||
assertNull(store().readyRoot)
|
||||
}
|
||||
|
||||
@Test fun rejectsUnsafeOrIncompleteInventories() {
|
||||
fun manifest(vararg paths: String) = GalaxyAssetManifest(paths.map { GalaxyAssetFile(it, "0".repeat(64), 1) })
|
||||
val complete = arrayOf("index.html", "js/boot.js", "js/app.js", "data/catalog.json")
|
||||
manifest(*complete).validate()
|
||||
for (bad in listOf(manifest(*complete, "js/../x.js"), manifest(*complete, "other/x.js"), manifest(*complete, "js/a b.js"),
|
||||
manifest("index.html", "js/app.js"), manifest(*complete, "data/runtime.json"))) {
|
||||
assertThrows(GalaxyUpdateException::class.java) { bad.validate() }
|
||||
}
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class GalaxyProbeTest {
|
||||
@Test fun acceptsOnlyAnAuthenticatedLocalGalaxyAcknowledgement() {
|
||||
assertTrue(GalaxyProbe.accepts(200, "application/json", authenticated = true, localAccess = true))
|
||||
assertTrue(GalaxyProbe.accepts(200, "application/json; charset=utf-8", authenticated = true, localAccess = true))
|
||||
assertFalse(GalaxyProbe.accepts(404, "application/json", authenticated = true, localAccess = true))
|
||||
assertFalse(GalaxyProbe.accepts(200, "text/html", authenticated = true, localAccess = true))
|
||||
assertFalse(GalaxyProbe.accepts(200, "application/json", authenticated = false, localAccess = true))
|
||||
assertFalse(GalaxyProbe.accepts(200, "application/json", authenticated = true, localAccess = false))
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class LanPairingTest {
|
||||
private class Api(val cookie: String?, val status: Int = 200, val body: String = "{}", val failSession: Boolean = false) : LanPairingApi {
|
||||
val posts = mutableListOf<Triple<String, String, String>>()
|
||||
override fun session(): String? { if (failSession) throw java.io.IOException("offline"); return cookie }
|
||||
override fun post(path: String, body: String, cookie: String): Pair<Int, String> { posts += Triple(path, body, cookie); return status to this.body }
|
||||
}
|
||||
|
||||
@Test fun opensTheWindowWithTheLocalSession() {
|
||||
val api = Api("galaxy_session=abc")
|
||||
assertNull(LanPairing.openWindow(api))
|
||||
assertEquals(listOf(Triple("/api/bluetooth/action", "{\"operation\":\"accept_pair\"}", "galaxy_session=abc")), api.posts)
|
||||
}
|
||||
|
||||
@Test fun retriesWhileCommaIsBusyThenSucceeds() {
|
||||
var busyAnswers = 2
|
||||
val pauses = mutableListOf<Long>()
|
||||
val api = object : LanPairingApi {
|
||||
override fun session(): String? = "c"
|
||||
override fun post(path: String, body: String, cookie: String): Pair<Int, String> =
|
||||
if (busyAnswers-- > 0) 409 to "{\"code\":\"busy\"}" else 200 to "{}"
|
||||
}
|
||||
assertNull(LanPairing.openWindow(api, pause = { pauses += it }))
|
||||
assertEquals(2, pauses.size)
|
||||
}
|
||||
|
||||
@Test fun readsTheCodeFromCommasSpacedJson() {
|
||||
val pauses = mutableListOf<Long>()
|
||||
assertEquals("comma answered HTTP 409 (busy)", LanPairing.openWindow(Api("c", 409, "{\"error\": \"x\", \"code\": \"busy\"}"), pause = { pauses += it }))
|
||||
assertEquals(3, pauses.size)
|
||||
}
|
||||
|
||||
@Test fun givesUpAfterTheLastBusyAnswerAndNeverRetriesOtherRefusals() {
|
||||
val pauses = mutableListOf<Long>()
|
||||
assertEquals("comma answered HTTP 409 (busy)", LanPairing.openWindow(Api("c", 409, "{\"code\":\"busy\"}"), pause = { pauses += it }))
|
||||
assertEquals(3, pauses.size)
|
||||
pauses.clear()
|
||||
assertEquals("comma answered HTTP 503 (radio_unavailable)", LanPairing.openWindow(Api("c", 503, "{\"code\":\"radio_unavailable\"}"), pause = { pauses += it }))
|
||||
assertTrue(pauses.isEmpty())
|
||||
assertEquals("comma gave this phone no local Galaxy session", LanPairing.openWindow(Api(null), pause = { pauses += it }))
|
||||
assertTrue(pauses.isEmpty())
|
||||
}
|
||||
|
||||
private class ReadyApi(val answers: MutableList<CommaReadiness?>, val cookie: String? = "c") : LanPairingApi {
|
||||
var asked = 0
|
||||
override fun session(): String? = cookie
|
||||
override fun post(path: String, body: String, cookie: String): Pair<Int, String> = 200 to "{}"
|
||||
override fun readiness(cookie: String): CommaReadiness? = answers[minOf(asked++, answers.size - 1)]
|
||||
}
|
||||
private fun answer(ready: Boolean, code: String) = CommaReadiness(ready, code, "msg $code")
|
||||
|
||||
@Test fun waitsOutBootAndBridgeStartThenProceeds() {
|
||||
val api = ReadyApi(mutableListOf(answer(false, "starting"), answer(false, "bridge_starting"), answer(true, "ready")))
|
||||
val waited = mutableListOf<String>()
|
||||
assertNull(LanPairing.waitUntilReady(api, onWait = { waited += it }, pause = {}))
|
||||
assertEquals(listOf("msg starting", "msg bridge_starting"), waited)
|
||||
}
|
||||
|
||||
@Test fun stopsAtOnceForBlockersSomeoneMustFixAndGivesUpAfterTheWaitLimit() {
|
||||
val parked = ReadyApi(mutableListOf(answer(false, "park_required")))
|
||||
assertEquals("park_required", LanPairing.waitUntilReady(parked, pause = { fail("must not wait") })!!.code)
|
||||
assertEquals("bluetooth_off", LanPairing.waitUntilReady(ReadyApi(mutableListOf(answer(false, "bluetooth_off"))), pause = { fail("must not wait") })!!.code)
|
||||
val stuck = ReadyApi(mutableListOf(answer(false, "bridge_starting")))
|
||||
val pauses = mutableListOf<Long>()
|
||||
assertEquals("bridge_starting", LanPairing.waitUntilReady(stuck, maxWaitMs = 9000, stepMs = 3000, pause = { pauses += it })!!.code)
|
||||
assertEquals(3, pauses.size)
|
||||
}
|
||||
|
||||
@Test fun anOlderCommaOrNoSessionNeverBlocksPairing() {
|
||||
assertNull(LanPairing.waitUntilReady(ReadyApi(mutableListOf(null)), pause = {}))
|
||||
assertNull(LanPairing.waitUntilReady(ReadyApi(mutableListOf(answer(false, "park_required")), cookie = null), pause = {}))
|
||||
}
|
||||
|
||||
@Test fun saysWhyTheWindowCouldNotBeOpened() {
|
||||
val none = Api(null)
|
||||
assertEquals("comma gave this phone no local Galaxy session", LanPairing.openWindow(none)); assertTrue(none.posts.isEmpty())
|
||||
assertEquals("comma answered HTTP 409 (busy)", LanPairing.openWindow(Api("c", 409, "{\"error\":\"x\",\"code\":\"busy\"}")))
|
||||
assertEquals("comma answered HTTP 503 (radio_unavailable)", LanPairing.openWindow(Api("c", 503, "{\"code\":\"radio_unavailable\"}")))
|
||||
assertEquals("comma answered HTTP 403", LanPairing.openWindow(Api("c", 403, "{\"error\":\"Remote Galaxy request denied\"}")))
|
||||
assertEquals("offline", LanPairing.openWindow(Api("c", failSession = true)))
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import link.firestar.companion.MusicBond.Outcome
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MusicBondTest {
|
||||
private val comma = "AA:BB:CC:DD:EE:FF"
|
||||
|
||||
private fun run(address: String = comma, bonded: MutableSet<String> = mutableSetOf(), attempts: Int = 5,
|
||||
bond: (String) -> Boolean = { true }, onPause: () -> Unit = {}): Pair<Outcome, List<String>> {
|
||||
val asked = mutableListOf<String>()
|
||||
val outcome = MusicBond({ bonded.toSet() }, { asked += it; bond(it) }, { onPause() }, attempts).run(address)
|
||||
return outcome to asked
|
||||
}
|
||||
|
||||
@Test fun olderCommaWithoutAnAddressIsSkippedQuietly() {
|
||||
assertEquals(Outcome.UNSUPPORTED to emptyList<String>(), run(""))
|
||||
assertEquals(Outcome.UNSUPPORTED to emptyList<String>(), run("not an address"))
|
||||
assertNull(MusicBond.message(Outcome.UNSUPPORTED))
|
||||
}
|
||||
|
||||
@Test fun anAlreadyBondedCommaIsNotBondedAgain() {
|
||||
assertEquals(Outcome.ALREADY_PAIRED to emptyList<String>(), run(bonded = mutableSetOf(comma)))
|
||||
assertEquals(Outcome.ALREADY_PAIRED to emptyList<String>(), run(address = comma.lowercase(), bonded = mutableSetOf(comma)))
|
||||
}
|
||||
|
||||
@Test fun bondingWaitsUntilAndroidReportsTheBond() {
|
||||
val bonded = mutableSetOf<String>()
|
||||
var pauses = 0
|
||||
val (outcome, asked) = run(bonded = bonded, onPause = { if (++pauses == 3) bonded += comma })
|
||||
assertEquals(Outcome.PAIRED, outcome)
|
||||
assertEquals(listOf(comma), asked)
|
||||
}
|
||||
|
||||
@Test fun refusedOrTimedOutBondsFail() {
|
||||
assertEquals(Outcome.FAILED, run(bond = { false }).first)
|
||||
assertEquals(Outcome.FAILED, run(attempts = 3).first)
|
||||
assertTrue(MusicBond.message(Outcome.FAILED)!!.contains("music wasn't set up"))
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class NetworksTest {
|
||||
@Test fun typedAddressAddsSchemeAndGalaxyPort() {
|
||||
assertEquals("http://192.168.1.10:8082", Networks.typedAddress(" 192.168.1.10 "))
|
||||
assertEquals("http://192.168.1.10:8082", Networks.typedAddress("192.168.1.10/"))
|
||||
assertEquals("http://10.0.0.4:8082", Networks.typedAddress("10.0.0.4:8082"))
|
||||
}
|
||||
|
||||
@Test fun typedAddressKeepsExplicitSchemeAndPortForValidation() {
|
||||
assertEquals("http://192.168.1.10:8082", Networks.typedAddress("http://192.168.1.10:8082"))
|
||||
assertEquals("https://192.168.1.10:8082", Networks.typedAddress("https://192.168.1.10"))
|
||||
assertEquals("http://192.168.1.10:9000", Networks.typedAddress("192.168.1.10:9000"))
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class PhoneGpsTest {
|
||||
private val fix = PhoneGps.Fix(40.0, -110.0, 5f, 1_790_000_000_000, altitude = 1200.0, speed = 20f, bearing = 90f, bearingAccuracy = 10f)
|
||||
|
||||
@Test fun sendsKnownValues() {
|
||||
val payload = PhoneGps.payload(fix, 300)!!
|
||||
assertEquals(40.0, payload["latitude"]); assertEquals(300L, payload["ageMs"]); assertEquals(90.0, payload["bearing"])
|
||||
assertFalse("speedAccuracy" in payload)
|
||||
}
|
||||
|
||||
@Test fun dropsBearingWithoutAccuracy() {
|
||||
val payload = PhoneGps.payload(fix.copy(bearingAccuracy = null), 300)!!
|
||||
assertFalse("bearing" in payload)
|
||||
}
|
||||
|
||||
@Test fun rejectsOldOrUnusableFixes() {
|
||||
assertNull(PhoneGps.payload(fix, 2500))
|
||||
assertNull(PhoneGps.payload(fix, -1))
|
||||
assertNull(PhoneGps.payload(fix.copy(accuracy = 0f), 300))
|
||||
assertNull(PhoneGps.payload(fix.copy(latitude = Double.NaN), 300))
|
||||
}
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
package link.firestar.companion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.*
|
||||
import java.net.*
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class SocksServerTest {
|
||||
private val loop = InetAddress.getByName("127.0.0.1") as Inet4Address
|
||||
private val publicIp = InetAddress.getByName("93.184.216.34")
|
||||
private class Transport(val remote: InetSocketAddress, val address: InetAddress) : CellularTransport {
|
||||
val lookups = mutableListOf<String>()
|
||||
override fun resolve(host: String): Array<InetAddress> { lookups.add(host); return arrayOf(address) }
|
||||
override fun socket(): Socket = object : Socket() {
|
||||
override fun connect(endpoint: SocketAddress, timeout: Int) { super.connect(remote, timeout) }
|
||||
}
|
||||
override fun datagram(): DatagramSocket = object : DatagramSocket() {
|
||||
override fun send(packet: DatagramPacket) { packet.socketAddress = remote; super.send(packet) }
|
||||
override fun receive(packet: DatagramPacket) { super.receive(packet); packet.address = address }
|
||||
}
|
||||
}
|
||||
private fun authenticate(socket: Socket, password: String = "password"): DataInputStream {
|
||||
socket.soTimeout = 2000
|
||||
val output = DataOutputStream(socket.getOutputStream())
|
||||
val input = DataInputStream(socket.getInputStream())
|
||||
output.write(byteArrayOf(5, 1, 2)); output.flush()
|
||||
assertEquals(5, input.readUnsignedByte()); assertEquals(2, input.readUnsignedByte())
|
||||
output.writeByte(1); output.writeByte(4); output.writeBytes("user"); output.writeByte(password.length); output.writeBytes(password); output.flush()
|
||||
assertEquals(1, input.readUnsignedByte()); assertEquals(if (password == "password") 0 else 1, input.readUnsignedByte())
|
||||
return input
|
||||
}
|
||||
private fun request(socket: Socket, command: Int, host: String, port: Int) {
|
||||
val output = DataOutputStream(socket.getOutputStream())
|
||||
output.write(byteArrayOf(5, command.toByte(), 0, 3, host.length.toByte()))
|
||||
output.writeBytes(host); output.writeShort(port); output.flush()
|
||||
}
|
||||
private fun response(input: DataInputStream, code: Int = 0): Int {
|
||||
assertEquals(5, input.readUnsignedByte()); assertEquals(code, input.readUnsignedByte()); assertEquals(0, input.readUnsignedByte())
|
||||
assertEquals(1, input.readUnsignedByte()); input.readInt(); return input.readUnsignedShort()
|
||||
}
|
||||
@Test fun domainConnectResolvesThroughCellularAndCountsBothDirections() {
|
||||
ServerSocket(0, 1, loop).use { remote ->
|
||||
val echo = Thread { remote.accept().use { socket -> val value = socket.getInputStream().read(); socket.getOutputStream().write(value) } }
|
||||
echo.start()
|
||||
val transport = Transport(InetSocketAddress(loop, remote.localPort), publicIp)
|
||||
val bytes = AtomicLong()
|
||||
SocksServer(loop, transport, "user", "password", { bytes.addAndGet(it.toLong()) }, "127.0.0.1", 0).use { server ->
|
||||
Socket(loop, server.port).use { socket ->
|
||||
val input = authenticate(socket)
|
||||
request(socket, 1, "api.mapbox.com", 443); response(input)
|
||||
socket.getOutputStream().write(42)
|
||||
assertEquals(42, input.read())
|
||||
assertEquals(listOf("api.mapbox.com"), transport.lookups)
|
||||
assertEquals(2L, bytes.get())
|
||||
}
|
||||
}
|
||||
echo.join(2000); assertFalse(echo.isAlive)
|
||||
}
|
||||
}
|
||||
@Test fun invalidCredentialsAndUploadHostsAreRejected() {
|
||||
val transport = Transport(InetSocketAddress(loop, 1), publicIp)
|
||||
SocksServer(loop, transport, "user", "password", {}, "127.0.0.1", 0).use { server ->
|
||||
Socket(loop, server.port).use { socket -> assertEquals(-1, authenticate(socket, "wrong").read()) }
|
||||
Socket(loop, server.port).use { socket ->
|
||||
val input = authenticate(socket)
|
||||
request(socket, 1, "upload.comma.ai", 443); response(input, 4)
|
||||
assertTrue(transport.lookups.isEmpty())
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test fun udpAssociationRelaysAndClosesWithControlSocket() {
|
||||
DatagramSocket(InetSocketAddress(loop, 0)).use { remote ->
|
||||
remote.soTimeout = 3000
|
||||
val echo = Thread {
|
||||
val packet = DatagramPacket(ByteArray(512), 512); remote.receive(packet); remote.send(packet)
|
||||
}
|
||||
echo.start()
|
||||
val transport = Transport(InetSocketAddress(loop, remote.localPort), publicIp)
|
||||
SocksServer(loop, transport, "user", "password", {}, "127.0.0.1", 0).use { server ->
|
||||
Socket(loop, server.port).use { control ->
|
||||
val input = authenticate(control)
|
||||
request(control, 3, "0.0.0.0", 0)
|
||||
val port = response(input)
|
||||
DatagramSocket(InetSocketAddress(loop, 0)).use { udp ->
|
||||
udp.soTimeout = 2000
|
||||
val frame = ByteArrayOutputStream()
|
||||
DataOutputStream(frame).apply {
|
||||
writeShort(0); writeByte(0); writeByte(3); writeByte(14); writeBytes("api.mapbox.com")
|
||||
writeShort(remote.localPort); writeBytes("hello")
|
||||
}
|
||||
// 14 includes the dot-separated hostname length.
|
||||
val data = frame.toByteArray()
|
||||
udp.send(DatagramPacket(data, data.size, loop, port))
|
||||
val packet = DatagramPacket(ByteArray(512), 512); udp.receive(packet)
|
||||
assertEquals("hello", packet.data.copyOfRange(10, packet.length).toString(Charsets.UTF_8))
|
||||
}
|
||||
}
|
||||
}
|
||||
echo.join(2000); assertFalse(echo.isAlive)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
000001d6000102030405060708090a0b4502d65bd8080d6cb295968bb6093b3bc5421ab86fb1b9c6b4ddd7169b2b469b223497ed158267d6edc9eb2142ebb0f1c6faf0dc4ef7b6cf0d0c3e5c49f7ab68cf82699a2aed027355c6e3be33872409daf04932558b5f7f7bc2036c2a38dd9b4275c485b566df2d91f35c8c3674e05af8a5293c6a4daf1306b71de015b84f2d90754fee188b7e0959a811e468971181a5486587635ac80dfb82929d7c5f93149511d8d372b3fae5c9ba6797645908267bd85c9927071ed01230711cca0a6932c22535093134a019cac6d42b49f14e73f061a7c99e743c8e31712b2466d0ce56a3b073eda4e3c10670082731ceff80d423c268440a1e4efb9ee0283bc7d6fcfbf9abb8fac7a00ed8fa44c569d048ddee3c5115e438d0d9fb2d5d822f63adc38e82844b1d6f4aa47d79d6256563fddc293463a22702ff149c6ea6b248e049fb90323bd4916c1d17b65c209bf0da5c825cece3edb86ef97ee0912ce7859e0e36b017d200e2b8a79d340c515cc0188a9cd06772208716128ffe611dd753e3a9a1d12abc3e216488ec2259937140c0b8f108ddf59458101fac2cde9fe1b8b5053469e782b4e4fc2fa9912f8722aa1c778f5ba588cb2de27b0f6118a5299f47d8ecd29fce5d4102331150679d
|
||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
||||
00000044000102030405060708090a0b4602d60bce08035a8041b787b5d9574a80e1abc88968dd8bc14788ea77c693230810aefcd3eebd99107383d9b9a5b55a74cb8288a6e876ef
|
||||
@@ -1 +0,0 @@
|
||||
{"body":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
|
||||
@@ -1 +0,0 @@
|
||||
0000002c000102030405060708090a0b4702d61bce9ee074e663adffc39c1d10af576f9812f1646a3cb26b45340d21e3
|
||||
@@ -1 +0,0 @@
|
||||
{"ok":true}
|
||||
@@ -1 +0,0 @@
|
||||
00000050000102030405060708090a0b4702d61bea9ee076e835ffe4d5cb424fc493d316dc592f1d4c0fc7bf3f4661c2683fcd93c2b173f61dcb11c2fbf3494c9b2a42f03157eec7fd74278ae26e6103c8e124c5
|
||||
@@ -1 +0,0 @@
|
||||
plugins { id("com.android.application") version "9.4.1" apply false }
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
ANDROID_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
export COMPANION_KEYSTORE="${COMPANION_KEYSTORE:-$HOME/.starpilot/companion.jks}"
|
||||
if [[ -z "${JAVA_HOME:-}" && -d '/Applications/Android Studio.app/Contents/jbr/Contents/Home' ]]; then
|
||||
export JAVA_HOME='/Applications/Android Studio.app/Contents/jbr/Contents/Home'
|
||||
fi
|
||||
export ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
|
||||
if [[ ! -f "$COMPANION_KEYSTORE" ]]; then
|
||||
echo 'Missing release signing key. Follow ../README.md to create it once; never commit it.' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "${COMPANION_KEY_PASSWORD:-}" ]]; then
|
||||
COMPANION_PASSWORD_FILE="${COMPANION_PASSWORD_FILE:-$HOME/.starpilot/companion-signing-password}"
|
||||
export COMPANION_KEY_PASSWORD="$(cat "$COMPANION_PASSWORD_FILE")"
|
||||
fi
|
||||
"$ANDROID_ROOT/gradlew" -p "$ANDROID_ROOT" --no-daemon assembleRelease lintRelease
|
||||
COMPANION_OUTPUT="$ANDROID_ROOT/../../galaxy/bin/starpilot-companion.apk"
|
||||
cp "$ANDROID_ROOT/app/build/outputs/apk/release/app-release.apk" "$COMPANION_OUTPUT"
|
||||
python3 - "$ANDROID_ROOT/app/build/outputs/apk/release/output-metadata.json" "$COMPANION_OUTPUT.version" <<'PY'
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
metadata = json.loads(pathlib.Path(sys.argv[1]).read_text())
|
||||
pathlib.Path(sys.argv[2]).write_text(metadata['elements'][0]['versionName'] + '\n')
|
||||
PY
|
||||
printf 'Release APK: %s\n' "$COMPANION_OUTPUT"
|
||||
@@ -1,47 +0,0 @@
|
||||
# Galaxy: StarPilot Privacy Policy
|
||||
|
||||
**Google Play listings:**
|
||||
- **Galaxy: StarPilot Companion**
|
||||
- **Galaxy: StarPilot Auto**
|
||||
|
||||
**Last updated:** October 27, 2026
|
||||
|
||||
This privacy policy applies to both **Galaxy: StarPilot Companion** and **Galaxy: StarPilot Auto**, Android applications for [StarPilot](https://github.com/StarPilotHQ/StarPilot), open-source driving software based on openpilot.
|
||||
|
||||
**Galaxy: StarPilot Companion** is the main Android application. It appears as **Galaxy** on your phone and displays the Galaxy interface served by StarPilot.
|
||||
|
||||
**Galaxy: StarPilot Auto** is a lightweight Android Auto companion that works alongside the main Galaxy app to display supported StarPilot features on your vehicle's Android Auto screen. It relies on the main Galaxy app for device communication and connectivity.
|
||||
|
||||
## Data used
|
||||
|
||||
The following describes how data is handled by the two applications.
|
||||
|
||||
- **Location (Galaxy Companion):** If you enable phone GPS sharing, Galaxy sends your location, accuracy, time, and available altitude, speed, and direction to StarPilot for navigation. Sharing can continue in the background with a notification. You can turn it off in Galaxy or revoke location permission in Android settings.
|
||||
|
||||
- **Bluetooth (Galaxy Companion):** Galaxy uses nearby-device access to pair and connect to StarPilot. It stores Bluetooth addresses and an encrypted pairing key on your phone, and sends your phone's name and pairing information to StarPilot.
|
||||
|
||||
- **App data (Galaxy Companion):** Galaxy stores connection settings and phone-internet usage totals on your phone. It loads the Galaxy interface from StarPilot over local HTTP and saves a copy for Bluetooth use.
|
||||
|
||||
- **Controls and shared content (Galaxy Companion):** Galaxy sends your settings and navigation requests to StarPilot. If you share text from another app through Android's Share menu, Galaxy sends it to StarPilot for navigation.
|
||||
|
||||
- **Android Auto communication (Galaxy Auto):** Galaxy: StarPilot Auto communicates with the main Galaxy app on your phone to send commands and receive device status and other information needed for the Android Auto interface. It does not independently establish Bluetooth or other device connections.
|
||||
|
||||
- **Android Auto controls (Galaxy Auto):** Actions performed through Android Auto are forwarded to the main Galaxy app for processing. The main app manages communication with StarPilot.
|
||||
|
||||
- **Network data:** Galaxy and StarPilot can use Wi-Fi or your phone's cellular data, depending on the connection and features in use. Mobile data usage and carrier charges may apply. Your carrier and services used through StarPilot, such as maps or cloud services, may process network traffic under their own privacy policies.
|
||||
|
||||
## Storage and deletion
|
||||
|
||||
**Galaxy: StarPilot Companion** stores pairing information, connection settings, and other data necessary for its operation. You can remove saved pairing information within the app.
|
||||
|
||||
**Galaxy: StarPilot Auto** may store minimal local settings and connection state required for Android Auto functionality. It relies on the main Galaxy app for device communication.
|
||||
|
||||
Clearing an application's storage or uninstalling it removes that application's locally stored data. Removing Galaxy: StarPilot Auto does not remove data stored by Galaxy: StarPilot Companion.
|
||||
|
||||
These actions do not remove data already held by StarPilot or other services.
|
||||
|
||||
## Contact
|
||||
|
||||
For privacy questions or requests, use the dedicated [StarPilot support ticket process](https://wiki.firestar.link/ticketsystem/) and ask for Android app support.
|
||||
|
||||
Alternatively, contact the developer using the email address listed on the respective Google Play Store page.
|
||||
Binary file not shown.
-10
@@ -1,10 +0,0 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
|
||||
-248
@@ -1,248 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# gradlew start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh gradlew
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
@@ -1,82 +0,0 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem gradlew startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||
setlocal EnableExtensions
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute gradlew
|
||||
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||
@rem which allows us to clear the local environment before executing the java command
|
||||
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
|
||||
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
@@ -1,4 +0,0 @@
|
||||
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
|
||||
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
|
||||
rootProject.name = "StarPilotCompanion"
|
||||
include(":app")
|
||||
@@ -1,28 +0,0 @@
|
||||
from pathlib import Path
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
ANDROID = "{http://schemas.android.com/apk/res/android}"
|
||||
MANIFEST = Path(__file__).parents[1] / "app/src/main/AndroidManifest.xml"
|
||||
|
||||
|
||||
def test_main_activity_handles_rotation_without_recreating_bluetooth_session():
|
||||
root = ET.parse(MANIFEST).getroot()
|
||||
activity = next(node for node in root.iter("activity") if node.get(ANDROID + "name") == ".MainActivity")
|
||||
changes = set(activity.get(ANDROID + "configChanges", "").split("|"))
|
||||
assert {"orientation", "screenSize", "screenLayout", "smallestScreenSize"} <= changes
|
||||
|
||||
|
||||
def test_in_app_updater_has_scoped_install_permission_and_receiver():
|
||||
root = ET.parse(MANIFEST).getroot()
|
||||
permissions = {node.get(ANDROID + "name") for node in root.findall("uses-permission")}
|
||||
assert "android.permission.REQUEST_INSTALL_PACKAGES" in permissions
|
||||
receiver = next(node for node in root.iter("receiver") if node.get(ANDROID + "name") == ".AppInstallReceiver")
|
||||
assert receiver.get(ANDROID + "exported") == "false"
|
||||
|
||||
|
||||
def test_update_completion_survives_replacement_without_exporting_receiver():
|
||||
root = ET.parse(MANIFEST).getroot()
|
||||
receiver = next(node for node in root.iter("receiver") if node.get(ANDROID + "name") == ".AppUpdateCompletion")
|
||||
assert receiver.get(ANDROID + "exported") == "false"
|
||||
assert {node.get(ANDROID + "name") for node in receiver.iter("action")} == {"android.intent.action.MY_PACKAGE_REPLACED"}
|
||||
@@ -1,24 +0,0 @@
|
||||
"""The Android app and the phone bridge must agree on the encrypted BLE wire format."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ANDROID = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ANDROID.parents[1] / 'galaxy_bluetooth/bridge'))
|
||||
import protocol
|
||||
|
||||
|
||||
def test_android_wire_vectors():
|
||||
# These fixtures are also consumed by BleWireTest on the JVM.
|
||||
root = ANDROID / 'app/src/test/resources/ble'
|
||||
key = bytes(range(32))
|
||||
for name in ('plain', 'compressed', 'compact'):
|
||||
frame = bytes.fromhex((root / f'{name}.hex').read_text())
|
||||
expected = json.loads((root / f'{name}.json').read_text())
|
||||
assert protocol.open_message(frame[4:], key, 'response') == expected
|
||||
frame = bytes.fromhex((root / 'request.hex').read_text())
|
||||
assert protocol.open_message(frame[4:], key, 'request') == {'method': 'GET', 'path': '/api/companion/status'}
|
||||
with pytest.raises(ValueError):
|
||||
protocol.open_message(frame[4:], key, 'response')
|
||||
@@ -1,59 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('../app/src/main/assets/bluetooth-fetch.js', import.meta.url), 'utf8')
|
||||
function environment() {
|
||||
const sent = [], canceled = []
|
||||
const scope = { Request, Response, URL, Uint8Array, Map, Promise, Error, DOMException, atob, btoa,
|
||||
location: { href: 'https://galaxy-app.invalid/', origin: 'https://galaxy-app.invalid' },
|
||||
StarPilotBLE: { request: (id, raw) => sent.push([id, JSON.parse(raw)]), cancel: id => canceled.push(id) },
|
||||
fetch: async () => new Response('asset'),
|
||||
}
|
||||
scope.window = scope
|
||||
vm.runInNewContext(source, scope)
|
||||
return { scope, sent, canceled }
|
||||
}
|
||||
const turn = () => new Promise(resolve => setImmediate(resolve))
|
||||
test('BLE forwards POST bytes once, preserves HTTP failure, and keeps assets local', async () => {
|
||||
const { scope, sent } = environment()
|
||||
const pending = scope.fetch('https://galaxy-app.invalid/api/settings/preview', {method: 'POST', body: '{"value":"é"}', headers: {'Content-Type': 'application/json'}})
|
||||
await turn()
|
||||
assert.equal(sent.length, 1)
|
||||
assert.equal(Buffer.from(sent[0][1].body, 'base64').toString(), '{"value":"é"}')
|
||||
scope.__galaxyBleReply(sent[0][0], {status: 409, headers: {'content-type': 'application/json'}, body: btoa('{"error":"Park first"}')})
|
||||
assert.equal((await pending).status, 409)
|
||||
assert.equal(await (await scope.fetch('https://galaxy-app.invalid/data/catalog.json')).text(), 'asset')
|
||||
assert.equal(sent.length, 1)
|
||||
await assert.rejects(scope.fetch('https://evil.test/api/settings/preview'), /External/)
|
||||
})
|
||||
test('cancellation does not replay mutations and late replies cannot resolve them', async () => {
|
||||
const { scope, sent, canceled } = environment()
|
||||
const controller = new AbortController()
|
||||
const pending = scope.fetch('https://galaxy-app.invalid/api/settings/confirm', {method: 'POST', body: '{}', signal: controller.signal})
|
||||
await turn()
|
||||
controller.abort()
|
||||
await assert.rejects(pending, /Check whether the change applied/)
|
||||
assert.deepEqual(canceled, [sent[0][0]])
|
||||
scope.__galaxyBleReply(sent[0][0], {status: 200, headers: {}, body: btoa('{}')})
|
||||
assert.equal(sent.length, 1)
|
||||
})
|
||||
|
||||
test('BLE reads live restart identity and refuses replay before sending a request', async () => {
|
||||
const { scope, sent } = environment()
|
||||
const pending = scope.fetch('https://galaxy-app.invalid/data/runtime.json')
|
||||
await turn()
|
||||
assert.equal(sent[0][1].path, '/api/companion/runtime')
|
||||
scope.__galaxyBleReply(sent[0][0], {status: 200, headers: {}, body: btoa('{"schemaVersion":1,"monitor":"local","instance":"boot-2"}')})
|
||||
assert.equal((await (await pending).json()).instance, 'boot-2')
|
||||
for (const path of ['/api/replay/start', '/api/replay/media?sequence=1', '/api/recordings/local', '/api/cameras/snapshot',
|
||||
'/api/starport/upload', '/api/spotify/upload', '/api/navigation/map/tiles/1/0/0.png', '/api/companion/app.apk', '/api/companion/uplink']) {
|
||||
const blocked = await scope.fetch('https://galaxy-app.invalid' + path)
|
||||
assert.equal(blocked.status, 501)
|
||||
const body = await blocked.json()
|
||||
assert.equal(body.code, 'bluetooth_unavailable')
|
||||
assert.match(body.error, /not available over Bluetooth.*Wi-Fi or LAN/)
|
||||
}
|
||||
assert.equal(sent.length, 1)
|
||||
})
|
||||
@@ -1,96 +0,0 @@
|
||||
"""Real Zeroconf validation of the phone bridge's LAN advertiser, as discovered by Android."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
ANDROID = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ANDROID.parents[1] / 'galaxy_bluetooth/vendor'))
|
||||
from zeroconf import ServiceInfo, NonUniqueNameException
|
||||
from zeroconf._utils.name import service_type_name
|
||||
|
||||
spec = importlib.util.spec_from_file_location('lan_discovery', ANDROID.parents[1] / 'galaxy_bluetooth/bridge/lan_discovery.py')
|
||||
assert spec is not None and spec.loader is not None
|
||||
lan_discovery = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(lan_discovery)
|
||||
|
||||
|
||||
def test_real_zeroconf_accepts_the_service_advertised_to_android():
|
||||
publishers = []
|
||||
interfaces = []
|
||||
|
||||
def factory(addresses):
|
||||
publisher = Mock()
|
||||
# Registration performs strict type validation, unlike the old mock-only tests.
|
||||
publisher.register_service.side_effect = lambda info, **_: service_type_name(info.name)
|
||||
publishers.append(publisher)
|
||||
interfaces.append(addresses)
|
||||
return publisher
|
||||
|
||||
advertisement = lan_discovery.Advertisement(factory, ServiceInfo)
|
||||
with patch.object(socket, 'gethostname', return_value='comma-test'):
|
||||
advertisement.update(['172.31.254.1', '192.168.1.25'])
|
||||
assert interfaces == [['172.31.254.1'], ['192.168.1.25']]
|
||||
for publisher, addresses in zip(publishers, interfaces, strict=True):
|
||||
info = publisher.register_service.call_args.args[0]
|
||||
assert info.type == lan_discovery.SERVICE
|
||||
assert info.parsed_addresses() == addresses
|
||||
assert info.port == 8082
|
||||
assert info.properties == {b'protocol': b'galaxy-lan-1'}
|
||||
assert publishers[0].register_service.call_args.args[0].server != publishers[1].register_service.call_args.args[0].server
|
||||
android = ANDROID / 'app/src/main/java/link/firestar/companion/LanDiscovery.kt'
|
||||
assert f'const val SERVICE = "{lan_discovery.SERVICE.removesuffix("local.")}"' in android.read_text()
|
||||
advertisement.update(['172.31.254.1', '192.168.1.25'])
|
||||
assert len(publishers) == 2
|
||||
advertisement.update([])
|
||||
advertisement.close()
|
||||
for publisher in publishers:
|
||||
publisher.close.assert_called_once()
|
||||
|
||||
|
||||
def test_partial_registration_failure_closes_all_publishers_and_can_retry():
|
||||
first, failed, retried = Mock(), Mock(), Mock()
|
||||
failed.register_service.side_effect = OSError('interface went away')
|
||||
advertisement = lan_discovery.Advertisement(Mock(side_effect=[first, failed, retried]), ServiceInfo)
|
||||
with pytest.raises(OSError):
|
||||
advertisement.update(['172.31.254.1', '192.168.1.25'])
|
||||
first.close.assert_called_once()
|
||||
failed.close.assert_called_once()
|
||||
assert advertisement.addresses == []
|
||||
advertisement.update(['192.168.1.26'])
|
||||
assert advertisement.addresses == ['192.168.1.26']
|
||||
advertisement.close()
|
||||
retried.close.assert_called_once()
|
||||
|
||||
|
||||
def test_long_device_hostname_stays_within_dns_label_limits():
|
||||
publisher = Mock()
|
||||
advertisement = lan_discovery.Advertisement(Mock(return_value=publisher), ServiceInfo)
|
||||
with patch.object(socket, 'gethostname', return_value='comma-' + 'x' * 100):
|
||||
advertisement.update(['192.168.100.200'])
|
||||
info = publisher.register_service.call_args.args[0]
|
||||
assert len(info.server.removesuffix('.local.')) <= 63
|
||||
assert service_type_name(info.name) == lan_discovery.SERVICE
|
||||
advertisement.close()
|
||||
|
||||
|
||||
def test_loop_retries_zeroconf_exceptions_without_crashing():
|
||||
discovery = lan_discovery
|
||||
failed, good = Mock(), Mock()
|
||||
failed.register_service.side_effect = NonUniqueNameException()
|
||||
# A cleanup error must not prevent cleanup of other publishers or retrying.
|
||||
failed.close.side_effect = RuntimeError('already stopped')
|
||||
advertisement = lan_discovery.Advertisement(Mock(side_effect=[failed, good]), ServiceInfo)
|
||||
stopped = Mock(is_set=Mock(side_effect=[False, False, True]))
|
||||
with patch.object(discovery, 'Advertisement', return_value=advertisement), \
|
||||
patch.object(discovery, 'local_addresses', return_value=['192.168.1.25']), \
|
||||
patch.object(discovery, 'galaxy_listening', return_value=True), \
|
||||
patch.object(discovery.threading, 'Event', return_value=stopped), \
|
||||
patch.object(discovery.signal, 'signal'):
|
||||
discovery.main()
|
||||
assert stopped.wait.call_count == 2
|
||||
good.register_service.assert_called_once()
|
||||
good.close.assert_called_once()
|
||||
@@ -1,49 +0,0 @@
|
||||
"""Real ARM64 mapped-DNS smoke test; run only inside a disposable container."""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import pathlib
|
||||
|
||||
|
||||
def main():
|
||||
config = {
|
||||
'tunnel': {'name': 'spuplink0', 'mtu': 1500, 'ipv4': '198.18.0.1'},
|
||||
'socks5': {'address': '172.31.254.10', 'port': 1080, 'udp': 'udp', 'username': 'a' * 32, 'password': 'b' * 32},
|
||||
'mapdns': {'address': '198.18.0.2', 'port': 53, 'network': '198.19.0.0', 'netmask': '255.255.0.0', 'cache-size': 10000},
|
||||
}
|
||||
pathlib.Path('/tmp/tunnel.json').write_text(json.dumps(config))
|
||||
p = subprocess.Popen(['/b/hev-socks5-tunnel_linux_arm64', '/tmp/tunnel.json'])
|
||||
try:
|
||||
for _ in range(50):
|
||||
if pathlib.Path('/sys/class/net/spuplink0').exists():
|
||||
break
|
||||
if p.poll() is not None:
|
||||
raise RuntimeError('tunnel process exited')
|
||||
time.sleep(0.1)
|
||||
subprocess.run(['ip', 'link', 'set', 'spuplink0', 'up'], check=True)
|
||||
subprocess.run(['ip', 'route', 'add', '198.18.0.0/15', 'dev', 'spuplink0'], check=True)
|
||||
for kind in (1, 28):
|
||||
question = b''.join(bytes([len(v)]) + v for v in [b'api', b'mapbox', b'com']) + b'\0' + struct.pack('!HH', kind, 1)
|
||||
wire = struct.pack('!HHHHHH', 123, 0x100, 1, 0, 0, 0) + question
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.settimeout(3)
|
||||
sock.sendto(wire, ('198.18.0.2', 53))
|
||||
result = sock.recv(4096)
|
||||
header = struct.unpack('!HHHHHH', result[:12])
|
||||
assert header[1] & 15 == 0, header
|
||||
if kind == 1:
|
||||
assert header[3] == 1
|
||||
assert result[-4:-2] == bytes([198, 19]), result
|
||||
else:
|
||||
assert header[3] == 0, header
|
||||
print('Mapped DNS', 'A' if kind == 1 else 'AAAA', 'PASS', header)
|
||||
finally:
|
||||
p.terminate()
|
||||
p.wait(timeout=5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,5 +0,0 @@
|
||||
build/
|
||||
DerivedData/
|
||||
*.xcuserstate
|
||||
xcuserdata/
|
||||
.DS_Store
|
||||
@@ -1,16 +0,0 @@
|
||||
# carplay testing
|
||||
|
||||
carplay support is in `GalaxyBluetooth/CarPlaySceneDelegate.swift`. it uses native CarPlay templates for the overview, temperatures, rates and Galaxy settings.
|
||||
|
||||
physical CarPlay needs Apple's approved entitlement and a matching signing profile. check the target's signing setup before testing; a TestFlight invitation alone does not provide the entitlement.
|
||||
|
||||
## check on a head unit
|
||||
|
||||
- open each top-level page and confirm values stay readable in light and dark mode.
|
||||
- open settings categories and use the top-bar arrows to reach the remaining pages.
|
||||
- check Back navigation and numeric controls. change and restore a display preference to confirm saving.
|
||||
- Disconnect and reconnect the phone. check that stale readings clear and the connection recovers.
|
||||
|
||||
keep initial tests parked. Share the head unit, iPhone/iOS version and a photo of any layout problem. Copy the app's connection reports after a failure.
|
||||
|
||||
the old Dom full-screen video capture instructions do not apply to SecretGood. carplay does not show a full comma-screen video stream.
|
||||
@@ -1,301 +0,0 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 56;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
C0AA00000000000000000007 /* Lucide-LICENSE.txt in Resources */ = {isa = PBXBuildFile; fileRef = C0AA00000000000000000008 /* Lucide-LICENSE.txt */; };
|
||||
C0AA00000000000000000005 /* Sora-OFL.txt in Resources */ = {isa = PBXBuildFile; fileRef = C0AA00000000000000000006 /* Sora-OFL.txt */; };
|
||||
C0AA00000000000000000003 /* Sora.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C0AA00000000000000000004 /* Sora.ttf */; };
|
||||
C0AA00000000000000000001 /* ConnectionSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AA00000000000000000002 /* ConnectionSettingsView.swift */; };
|
||||
D92135C445C249E6A5DC0011 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D92135C445C249E6A5DC0012 /* PrivacyInfo.xcprivacy */; };
|
||||
140107256F4F4DF2910BED61 /* BluetoothTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = D47658A09FCC6A6C73D1A1A3 /* BluetoothTransport.swift */; };
|
||||
1698566BBEF2185D9C80B6BB /* HTTP.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34DE7063A67F0755E6E69BF7 /* HTTP.swift */; };
|
||||
28D504D2BD92FF8A8AEB68A7 /* CompanionDiagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AD85D1A585138AF80FEADB9 /* CompanionDiagnostics.swift */; };
|
||||
36EBF9BB2BE027F139572ADA /* GalaxyBluetoothApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3356A9DC86451A9D92F074F8 /* GalaxyBluetoothApp.swift */; };
|
||||
5992DC6B04748581DE47AA02 /* LoopbackServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = B07071562661895558F74EE6 /* LoopbackServer.swift */; };
|
||||
606A672A792903E98EFFC2D9 /* Resources/Branding.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9F0B8B04FE0E80BA046C0042 /* Resources/Branding.xcassets */; };
|
||||
754B6F8C853BDD47D7593948 /* NetworkTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 114E3D37646B3A8626A8A232 /* NetworkTransport.swift */; };
|
||||
7F54642B30B38C648001D4ED /* Wire.swift in Sources */ = {isa = PBXBuildFile; fileRef = F48B8D06AA8D8C4AC21E5982 /* Wire.swift */; };
|
||||
887D84D1E3F00F0A5A8AD090 /* PrivateLANHTTP.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5492C1BC71EB8D0DBF12896E /* PrivateLANHTTP.swift */; };
|
||||
8BA587954B4079F504AAD35E /* GalaxyRequestTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80D0F5CDB02B33E408C75D8C /* GalaxyRequestTransport.swift */; };
|
||||
A6D597850E6DD0CDFB754EF8 /* CarPlaySceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F213860FC7A532DBD355109 /* CarPlaySceneDelegate.swift */; };
|
||||
B2DE76B1CE686BDFB635FAAE /* GalaxyAssetStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3BBE1488FD8A83E3983FEDE /* GalaxyAssetStore.swift */; };
|
||||
BC3706D8A74BDB5B0AA8063E /* PairingKeyStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43A1199899003FF3F5F30831 /* PairingKeyStore.swift */; };
|
||||
DE64BADD40C934E610D4D505 /* GalaxyWebView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF41C7E4AB86DEB71B85E4F6 /* GalaxyWebView.swift */; };
|
||||
FACE00000000000000000001 /* PairingCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = FACE00000000000000000002 /* PairingCode.swift */; };
|
||||
C1A100000000000000000001 /* ClaimPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A100000000000000000002 /* ClaimPairing.swift */; };
|
||||
D15C00000000000000000001 /* LANDiscovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = D15C00000000000000000002 /* LANDiscovery.swift */; };
|
||||
D15C00000000000000000011 /* AudioPairing.swift in Sources */ = {isa = PBXBuildFile; fileRef = D15C00000000000000000012 /* AudioPairing.swift */; };
|
||||
D15C00000000000000000013 /* AudioPairingSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = D15C00000000000000000014 /* AudioPairingSheet.swift */; };
|
||||
D15C00000000000000000015 /* PhoneLocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = D15C00000000000000000016 /* PhoneLocation.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C0AA00000000000000000008 /* Lucide-LICENSE.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = Resources/Lucide-LICENSE.txt; sourceTree = "<group>"; };
|
||||
C0AA00000000000000000006 /* Sora-OFL.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = Resources/Sora-OFL.txt; sourceTree = "<group>"; };
|
||||
C0AA00000000000000000004 /* Sora.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = Resources/Sora.ttf; sourceTree = "<group>"; };
|
||||
C0AA00000000000000000002 /* ConnectionSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionSettingsView.swift; sourceTree = "<group>"; };
|
||||
D92135C445C249E6A5DC0012 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
114E3D37646B3A8626A8A232 /* NetworkTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkTransport.swift; sourceTree = "<group>"; };
|
||||
3356A9DC86451A9D92F074F8 /* GalaxyBluetoothApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalaxyBluetoothApp.swift; sourceTree = "<group>"; };
|
||||
34DE7063A67F0755E6E69BF7 /* HTTP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTP.swift; sourceTree = "<group>"; };
|
||||
43A1199899003FF3F5F30831 /* PairingKeyStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingKeyStore.swift; sourceTree = "<group>"; };
|
||||
5492C1BC71EB8D0DBF12896E /* PrivateLANHTTP.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivateLANHTTP.swift; sourceTree = "<group>"; };
|
||||
80D0F5CDB02B33E408C75D8C /* GalaxyRequestTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalaxyRequestTransport.swift; sourceTree = "<group>"; };
|
||||
8AD85D1A585138AF80FEADB9 /* CompanionDiagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanionDiagnostics.swift; sourceTree = "<group>"; };
|
||||
8F213860FC7A532DBD355109 /* CarPlaySceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CarPlaySceneDelegate.swift; sourceTree = "<group>"; };
|
||||
9CEEC13202AFBF12EE3ABB99 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
9F0B8B04FE0E80BA046C0042 /* Resources/Branding.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Resources/Branding.xcassets; sourceTree = "<group>"; };
|
||||
A172CEDCAE47474B615C54D5 /* GalaxyBluetooth.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; path = GalaxyBluetooth.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
B07071562661895558F74EE6 /* LoopbackServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopbackServer.swift; sourceTree = "<group>"; };
|
||||
BF41C7E4AB86DEB71B85E4F6 /* GalaxyWebView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalaxyWebView.swift; sourceTree = "<group>"; };
|
||||
D3BBE1488FD8A83E3983FEDE /* GalaxyAssetStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GalaxyAssetStore.swift; sourceTree = "<group>"; };
|
||||
D47658A09FCC6A6C73D1A1A3 /* BluetoothTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BluetoothTransport.swift; sourceTree = "<group>"; };
|
||||
F48B8D06AA8D8C4AC21E5982 /* Wire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Wire.swift; sourceTree = "<group>"; };
|
||||
FACE00000000000000000002 /* PairingCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingCode.swift; sourceTree = "<group>"; };
|
||||
C1A100000000000000000002 /* ClaimPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaimPairing.swift; sourceTree = "<group>"; };
|
||||
D15C00000000000000000002 /* LANDiscovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LANDiscovery.swift; sourceTree = "<group>"; };
|
||||
D15C00000000000000000012 /* AudioPairing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioPairing.swift; sourceTree = "<group>"; };
|
||||
D15C00000000000000000014 /* AudioPairingSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioPairingSheet.swift; sourceTree = "<group>"; };
|
||||
D15C00000000000000000016 /* PhoneLocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhoneLocation.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
E2AA269EB967A8853A258BFA /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
0A3E27B8CA818264D75C8D81 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A172CEDCAE47474B615C54D5 /* GalaxyBluetooth.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
9E61AFF607A3704A97803240 /* GalaxyBluetooth */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D92135C445C249E6A5DC0012 /* PrivacyInfo.xcprivacy */,
|
||||
D15C00000000000000000002 /* LANDiscovery.swift */,
|
||||
D15C00000000000000000014 /* AudioPairingSheet.swift */,
|
||||
D15C00000000000000000012 /* AudioPairing.swift */,
|
||||
D15C00000000000000000016 /* PhoneLocation.swift */,
|
||||
114E3D37646B3A8626A8A232 /* NetworkTransport.swift */,
|
||||
D3BBE1488FD8A83E3983FEDE /* GalaxyAssetStore.swift */,
|
||||
5492C1BC71EB8D0DBF12896E /* PrivateLANHTTP.swift */,
|
||||
D47658A09FCC6A6C73D1A1A3 /* BluetoothTransport.swift */,
|
||||
FACE00000000000000000002 /* PairingCode.swift */,
|
||||
C1A100000000000000000002 /* ClaimPairing.swift */,
|
||||
3356A9DC86451A9D92F074F8 /* GalaxyBluetoothApp.swift */,
|
||||
C0AA00000000000000000002 /* ConnectionSettingsView.swift */,
|
||||
C0AA00000000000000000004 /* Sora.ttf */,
|
||||
C0AA00000000000000000006 /* Sora-OFL.txt */,
|
||||
C0AA00000000000000000008 /* Lucide-LICENSE.txt */,
|
||||
80D0F5CDB02B33E408C75D8C /* GalaxyRequestTransport.swift */,
|
||||
BF41C7E4AB86DEB71B85E4F6 /* GalaxyWebView.swift */,
|
||||
34DE7063A67F0755E6E69BF7 /* HTTP.swift */,
|
||||
B07071562661895558F74EE6 /* LoopbackServer.swift */,
|
||||
43A1199899003FF3F5F30831 /* PairingKeyStore.swift */,
|
||||
F48B8D06AA8D8C4AC21E5982 /* Wire.swift */,
|
||||
9CEEC13202AFBF12EE3ABB99 /* Info.plist */,
|
||||
8AD85D1A585138AF80FEADB9 /* CompanionDiagnostics.swift */,
|
||||
8F213860FC7A532DBD355109 /* CarPlaySceneDelegate.swift */,
|
||||
9F0B8B04FE0E80BA046C0042 /* Resources/Branding.xcassets */,
|
||||
);
|
||||
path = GalaxyBluetooth;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C69913C7EE4DFDD011BE172F = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
9E61AFF607A3704A97803240 /* GalaxyBluetooth */,
|
||||
0A3E27B8CA818264D75C8D81 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
34A04005BCAF206EEC990BD9 /* GalaxyBluetooth */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = EE8ED050E3386ACB51F5825B /* Build configuration list for PBXNativeTarget "GalaxyBluetooth" */;
|
||||
buildPhases = (
|
||||
878A52FC5FF6A57D50B7B870 /* Sources */,
|
||||
E2AA269EB967A8853A258BFA /* Frameworks */,
|
||||
41D311A605520FC7B8B9A980 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = GalaxyBluetooth;
|
||||
productName = GalaxyBluetooth;
|
||||
productReference = A172CEDCAE47474B615C54D5 /* GalaxyBluetooth.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
244210E48437B6556980A702 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1600;
|
||||
};
|
||||
buildConfigurationList = 442D61E217DD044EA4245BF2 /* Build configuration list for PBXProject "GalaxyBluetooth" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = C69913C7EE4DFDD011BE172F;
|
||||
productRefGroup = 0A3E27B8CA818264D75C8D81 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
34A04005BCAF206EEC990BD9 /* GalaxyBluetooth */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
41D311A605520FC7B8B9A980 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
D92135C445C249E6A5DC0011 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
606A672A792903E98EFFC2D9 /* Resources/Branding.xcassets in Resources */,
|
||||
C0AA00000000000000000003 /* Sora.ttf in Resources */,
|
||||
C0AA00000000000000000005 /* Sora-OFL.txt in Resources */,
|
||||
C0AA00000000000000000007 /* Lucide-LICENSE.txt in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
878A52FC5FF6A57D50B7B870 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
D15C00000000000000000001 /* LANDiscovery.swift in Sources */,
|
||||
D15C00000000000000000013 /* AudioPairingSheet.swift in Sources */,
|
||||
D15C00000000000000000011 /* AudioPairing.swift in Sources */,
|
||||
D15C00000000000000000015 /* PhoneLocation.swift in Sources */,
|
||||
754B6F8C853BDD47D7593948 /* NetworkTransport.swift in Sources */,
|
||||
B2DE76B1CE686BDFB635FAAE /* GalaxyAssetStore.swift in Sources */,
|
||||
887D84D1E3F00F0A5A8AD090 /* PrivateLANHTTP.swift in Sources */,
|
||||
140107256F4F4DF2910BED61 /* BluetoothTransport.swift in Sources */,
|
||||
FACE00000000000000000001 /* PairingCode.swift in Sources */,
|
||||
C1A100000000000000000001 /* ClaimPairing.swift in Sources */,
|
||||
28D504D2BD92FF8A8AEB68A7 /* CompanionDiagnostics.swift in Sources */,
|
||||
A6D597850E6DD0CDFB754EF8 /* CarPlaySceneDelegate.swift in Sources */,
|
||||
36EBF9BB2BE027F139572ADA /* GalaxyBluetoothApp.swift in Sources */,
|
||||
C0AA00000000000000000001 /* ConnectionSettingsView.swift in Sources */,
|
||||
8BA587954B4079F504AAD35E /* GalaxyRequestTransport.swift in Sources */,
|
||||
DE64BADD40C934E610D4D505 /* GalaxyWebView.swift in Sources */,
|
||||
1698566BBEF2185D9C80B6BB /* HTTP.swift in Sources */,
|
||||
5992DC6B04748581DE47AA02 /* LoopbackServer.swift in Sources */,
|
||||
BC3706D8A74BDB5B0AA8063E /* PairingKeyStore.swift in Sources */,
|
||||
7F54642B30B38C648001D4ED /* Wire.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
35B1014F135DE9B45529B733 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
488864B3D19480A82F7F1786 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
952548237D7F645F11D1E7B6 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = GalaxyBluetooth/CarPlay.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = 5P9DLC338G;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
INFOPLIST_FILE = GalaxyBluetooth/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = link.galaxy.bluetooth.natehuby76;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
E2D3A31BEAA1368FC62DA77A /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_ENTITLEMENTS = GalaxyBluetooth/CarPlay.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = 5P9DLC338G;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
INFOPLIST_FILE = GalaxyBluetooth/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = link.galaxy.bluetooth.natehuby76;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
442D61E217DD044EA4245BF2 /* Build configuration list for PBXProject "GalaxyBluetooth" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
488864B3D19480A82F7F1786 /* Debug */,
|
||||
35B1014F135DE9B45529B733 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
EE8ED050E3386ACB51F5825B /* Build configuration list for PBXNativeTarget "GalaxyBluetooth" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
952548237D7F645F11D1E7B6 /* Debug */,
|
||||
E2D3A31BEAA1368FC62DA77A /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 244210E48437B6556980A702 /* Project object */;
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1600"
|
||||
version = "1.7">
|
||||
<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">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
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">
|
||||
</BuildableReference>
|
||||
</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">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,149 +0,0 @@
|
||||
import Foundation
|
||||
#if os(iOS)
|
||||
import AVFAudio
|
||||
#endif
|
||||
|
||||
/// After this iPhone is paired for Galaxy, also pair it with comma for Bluetooth music.
|
||||
/// iOS apps cannot start a classic Bluetooth pairing, so comma opens a short window and the
|
||||
/// person taps comma in Settings → Bluetooth. Comma accepts only one phone and needs the code approved.
|
||||
@MainActor
|
||||
final class AudioPairing: ObservableObject {
|
||||
enum Phase: Equatable {
|
||||
case idle
|
||||
case opening
|
||||
case waiting(commaName: String)
|
||||
case confirm(code: String, promptID: String, commaName: String)
|
||||
case done
|
||||
case connected
|
||||
case message(String)
|
||||
}
|
||||
|
||||
struct Snapshot: Equatable {
|
||||
var adapterAddress: String
|
||||
var adapterName: String
|
||||
var state: String?
|
||||
var promptID: String?
|
||||
var promptKind: String?
|
||||
var code: String
|
||||
var displayOnly: Bool
|
||||
}
|
||||
|
||||
@Published private(set) var phase: Phase = .idle
|
||||
private let transport: () -> (any GalaxyRequestTransport)?
|
||||
private let pause: () async -> Void
|
||||
private let audioOutput: (String) -> Bool
|
||||
private let attempts: Int
|
||||
private var task: Task<Void, Never>?
|
||||
|
||||
init(transport: @escaping () -> (any GalaxyRequestTransport)?, attempts: Int = 125,
|
||||
audioOutput: ((String) -> Bool)? = nil,
|
||||
pause: @escaping () async -> Void = { try? await Task.sleep(nanoseconds: 1_000_000_000) }) {
|
||||
self.transport = transport; self.attempts = attempts; self.pause = pause; self.audioOutput = audioOutput ?? { AudioPairing.isAudioOutput($0) }
|
||||
}
|
||||
|
||||
static func isAudioOutput(_ commaName: String) -> Bool {
|
||||
#if os(iOS)
|
||||
return AVAudioSession.sharedInstance().currentRoute.outputs.contains {
|
||||
$0.portType == .bluetoothA2DP && $0.portName == commaName
|
||||
}
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
var active: Bool { phase != .idle }
|
||||
|
||||
nonisolated static func validAddress(_ value: String) -> Bool {
|
||||
value.range(of: "^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$", options: .regularExpression) != nil
|
||||
}
|
||||
|
||||
/// Only the window this phone opened counts; any other pairing belongs to someone else.
|
||||
nonisolated static func parse(_ data: Data) -> Snapshot? {
|
||||
guard let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
|
||||
let pairing = (value["pairing"] as? [String: Any]).flatMap { ($0["incoming"] as? Bool) == true ? $0 : nil }
|
||||
let prompt = pairing?["prompt"] as? [String: Any]
|
||||
return Snapshot(adapterAddress: (value["adapterAddress"] as? String) ?? "", adapterName: (value["adapterName"] as? String) ?? "",
|
||||
state: pairing?["state"] as? String, promptID: prompt?["id"] as? String, promptKind: prompt?["kind"] as? String,
|
||||
code: (prompt?["value"] as? String) ?? "", displayOnly: (prompt?["displayOnly"] as? Bool) ?? false)
|
||||
}
|
||||
|
||||
/// `windowOpen`: comma's pairing window is already open because the person just paired the app from comma's Pair phone.
|
||||
func start(windowOpen: Bool = false) {
|
||||
guard task == nil else { return }
|
||||
phase = .opening
|
||||
task = Task { [weak self] in
|
||||
await self?.run(windowOpen: windowOpen)
|
||||
self?.task = nil
|
||||
}
|
||||
}
|
||||
|
||||
func respond(accepted: Bool) {
|
||||
guard case .confirm(_, let promptID, let name) = phase else { return }
|
||||
phase = .waiting(commaName: name)
|
||||
Task { [weak self] in
|
||||
guard let self else { return }
|
||||
_ = try? await self.post(["operation": "pairing_response", "promptId": promptID, "accepted": accepted])
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
let wasOpen = phase != .idle && phase != .done && phase != .connected
|
||||
phase = .idle
|
||||
if wasOpen { Task { [weak self] in _ = try? await self?.post(["operation": "cancel_pair"]) } }
|
||||
}
|
||||
|
||||
func dismiss() { if case .message = phase { phase = .idle } else if phase == .done || phase == .connected { phase = .idle } else { cancel() } }
|
||||
|
||||
private func post(_ payload: [String: Any]) async throws -> BridgeResponse? {
|
||||
guard let transport = transport(), transport.connected else { return nil }
|
||||
let body = try JSONSerialization.data(withJSONObject: payload)
|
||||
return try await transport.request(path: "/api/bluetooth/action", method: "POST",
|
||||
headers: ["Content-Type": "application/json"], body: body)
|
||||
}
|
||||
|
||||
private func status() async -> Snapshot? {
|
||||
guard let transport = transport(), transport.connected,
|
||||
let response = try? await transport.request(path: "/api/bluetooth/status", method: "GET", headers: [:], body: Data()),
|
||||
response.status == 200 else { return nil }
|
||||
return Self.parse(response.bodyData)
|
||||
}
|
||||
|
||||
private func run(windowOpen: Bool) async {
|
||||
guard let first = await status() else { phase = .message("Phone music wasn't set up. Connect to your comma and try again."); return }
|
||||
// An older comma reports no adapter address and has no pairing window.
|
||||
guard Self.validAddress(first.adapterAddress) else { phase = .idle; return }
|
||||
let name = first.adapterName.isEmpty ? "comma" : first.adapterName
|
||||
if audioOutput(name) { phase = .connected; return }
|
||||
if !windowOpen {
|
||||
let opened: BridgeResponse?
|
||||
do { opened = try await post(["operation": "accept_pair"]) } catch { opened = nil }
|
||||
switch opened?.status {
|
||||
case 200?: break
|
||||
case 400?: phase = .idle; return
|
||||
case 409?: phase = .message("Phone music wasn't set up because comma's Bluetooth is busy. Park, stop Android Auto pairing, then try Set up phone music again."); return
|
||||
default: phase = .message("Phone music wasn't set up. Try Set up phone music again."); return
|
||||
}
|
||||
}
|
||||
phase = .waiting(commaName: name)
|
||||
var answered: String?
|
||||
for _ in 0..<attempts {
|
||||
await pause()
|
||||
if Task.isCancelled { return }
|
||||
if audioOutput(name) { phase = .connected; return }
|
||||
guard let current = await status() else { continue }
|
||||
if let id = current.promptID, !current.displayOnly, current.promptKind == "confirmation", id != answered {
|
||||
answered = id
|
||||
phase = .confirm(code: current.code, promptID: id, commaName: name)
|
||||
}
|
||||
switch current.state {
|
||||
case "paired"?: phase = .done; return
|
||||
case "failed"?, "canceled"?:
|
||||
phase = .message("Phone music pairing didn't finish. Try Set up phone music again."); return
|
||||
default: break
|
||||
}
|
||||
}
|
||||
phase = .message("The pairing window closed. Try Set up phone music again.")
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct AudioPairingSheet: View {
|
||||
@ObservedObject var pairing: AudioPairing
|
||||
let close: () -> Void
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 18) {
|
||||
Image(systemName: "music.note").font(.system(size: 40))
|
||||
Text("Bluetooth music").font(.title3.weight(.semibold))
|
||||
switch pairing.phase {
|
||||
case .idle, .opening:
|
||||
ProgressView("Asking comma to open pairing…")
|
||||
case .waiting(let name):
|
||||
Text("On your iPhone, open **Settings → Bluetooth** and select **\(name)** to pair music.")
|
||||
.multilineTextAlignment(.center)
|
||||
ProgressView()
|
||||
Text("Already says Connected? In Control Center, check whether comma is available as an audio output.")
|
||||
.font(.callout).multilineTextAlignment(.center)
|
||||
case .confirm(let code, _, _):
|
||||
Text("Check that comma and this iPhone both show").multilineTextAlignment(.center)
|
||||
Text(code).font(.system(size: 34, weight: .semibold, design: .monospaced))
|
||||
HStack {
|
||||
Button("Cancel") { pairing.respond(accepted: false) }.buttonStyle(.bordered)
|
||||
Button("Pair") { pairing.respond(accepted: true) }.buttonStyle(.borderedProminent)
|
||||
}
|
||||
case .done:
|
||||
Text("Bluetooth music paired. In Control Center, choose comma as the audio output.").multilineTextAlignment(.center)
|
||||
case .connected:
|
||||
Text("Music connected. This iPhone is already using comma as its Bluetooth audio output.").multilineTextAlignment(.center)
|
||||
case .message(let text):
|
||||
Text(text).multilineTextAlignment(.center)
|
||||
}
|
||||
Button((pairing.phase == .done || pairing.phase == .connected) ? "Done" : "Close") { close() }.padding(.top, 6)
|
||||
}.padding(24).presentationDetents([.medium, .large])
|
||||
}
|
||||
}
|
||||
@@ -1,579 +0,0 @@
|
||||
import Foundation
|
||||
import Combine
|
||||
import CoreBluetooth
|
||||
import CryptoKit
|
||||
import UIKit
|
||||
|
||||
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
|
||||
var onEvent: ((String) -> Void)?
|
||||
@Published var connected = false
|
||||
@Published var connecting = false
|
||||
@Published private(set) var fastReadFallback = false
|
||||
@Published var fastReads = UserDefaults.standard.bool(forKey: "galaxy.bluetooth.fastReads") {
|
||||
didSet {
|
||||
UserDefaults.standard.set(fastReads, forKey: "galaxy.bluetooth.fastReads")
|
||||
if fastReads != oldValue {
|
||||
fastReadFallback = false
|
||||
onEvent?("Bluetooth read mode: \(fastReads ? "experimental notifications" : "read stream"); applies to the next request")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 priorityStreak = 0
|
||||
private var requestStarted = 0.0
|
||||
private var receivedPackets = 0
|
||||
private var receivedWireBytes = 0
|
||||
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 phone: BridgePhone?
|
||||
let enqueuedAt = ProcessInfo.processInfo.systemUptime
|
||||
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 { onEvent?("Bluetooth scan blocked: state=\(central.state.rawValue)"); status = "Bluetooth is unavailable or permission is required."; return }
|
||||
devices = []
|
||||
peripherals = [:]
|
||||
onEvent?("Bluetooth service scan started; timeout=15s")
|
||||
for found in central.retrieveConnectedPeripherals(withServices: [CBUUID(string: Wire.service)]) {
|
||||
peripherals[found.identifier] = found
|
||||
devices.append(NearbyDevice(id: found.identifier, name: found.name ?? "Galaxy", signal: 0))
|
||||
}
|
||||
onEvent?("Bluetooth scan found \(devices.count) already-connected service candidates")
|
||||
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.onEvent?("Bluetooth service scan finished: candidates=\(self.devices.count)")
|
||||
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)…"
|
||||
onEvent?("Starting Bluetooth connection")
|
||||
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(reason: String = "Bluetooth connection closed") {
|
||||
let wasConnected = connected
|
||||
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
|
||||
priorityStreak = 0
|
||||
catalogSHA256 = nil
|
||||
supportsReadStream = false
|
||||
activeReadStream = false
|
||||
supportsNotifications = false
|
||||
activeNotifications = false
|
||||
pairingVerified = false
|
||||
notificationBuffer = []
|
||||
if wasConnected { onEvent?(reason) }
|
||||
}
|
||||
|
||||
private func failConnection(_ message: String) {
|
||||
if Self.shouldPauseFastReads(method: active?.method, notifications: activeNotifications,
|
||||
cancelled: message.lowercased().contains("cancelled")) {
|
||||
fastReadFallback = true
|
||||
onEvent?("Fast Bluetooth reads paused after a transfer failure. Reliable reads will be used after reconnecting; toggle fast reads off and on to retry.")
|
||||
}
|
||||
let lower = message.lowercased()
|
||||
let reason: String
|
||||
if lower.contains("request timed out") { reason = "Bluetooth request timed out" }
|
||||
else if lower.contains("push stalled") { reason = "Bluetooth notification transfer stalled" }
|
||||
else if lower.contains("cancelled") { reason = "Bluetooth request cancelled during transfer" }
|
||||
else if lower.contains("timed out") { reason = "Bluetooth connection timed out" }
|
||||
else if lower.contains("pairing") { reason = "Bluetooth pairing or authentication failed" }
|
||||
else if lower.contains("encrypt") || lower.contains("verify bluetooth") { reason = "Bluetooth encrypted response failed" }
|
||||
else { reason = "Bluetooth connection failed" }
|
||||
if let active {
|
||||
onEvent?("\(reason): \(active.method) \(LoopbackServer.reportPath(active.path)), queued=\(queue.count), sent=\(writeIndex)/\(outgoing.count), received packets=\(notificationCount), awaiting ack=\(awaitingAck)")
|
||||
}
|
||||
disconnect(reason: reason)
|
||||
onEvent?(reason)
|
||||
status = message
|
||||
}
|
||||
|
||||
func request(path: String, method: String, headers: [String: String], body: Data) async throws -> BridgeResponse {
|
||||
try await request(path: path, method: method, headers: headers, body: body, phone: nil)
|
||||
}
|
||||
|
||||
private func request(path: String, method: String, headers: [String: String], body: Data,
|
||||
phone: BridgePhone?) 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, phone: phone, 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 Self.canDrainCancellation(method: active?.method, requestSent: writeIndex >= outgoing.count) {
|
||||
// Finish read-only requests even if their outgoing frame is still being sent.
|
||||
activeCancelled = true
|
||||
} else {
|
||||
failConnection("Request cancelled. Reconnect before sending another request.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func canDrainCancellation(method: String?, requestSent: Bool) -> Bool {
|
||||
method == "GET" || requestSent
|
||||
}
|
||||
|
||||
static func useNotifications(method: String, path: String, supported: Bool, fastReads: Bool = false) -> Bool {
|
||||
supported && (method != "GET" || fastReads) && path != "/_bridge/health"
|
||||
}
|
||||
|
||||
static func shouldPauseFastReads(method: String?, notifications: Bool, cancelled: Bool) -> Bool {
|
||||
method == "GET" && notifications && !cancelled
|
||||
}
|
||||
|
||||
static func backgroundRead(_ path: String) -> Bool {
|
||||
let endpoint = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path
|
||||
return ["/api/device/state", "/api/system/monitor", "/api/local-access", "/api/models/status", "/api/software/status", "/api/drives/stats"].contains(endpoint)
|
||||
}
|
||||
|
||||
static func nextRequestIndex(methods: [String], paths: [String], priorityStreak: Int) -> Int {
|
||||
guard methods.count == paths.count, !methods.isEmpty, methods[0] == "GET", priorityStreak < 3 else { return 0 }
|
||||
// A queued write is a barrier: never move a read from after it to before it.
|
||||
for index in methods.indices {
|
||||
if methods[index] != "GET" { break }
|
||||
if !backgroundRead(paths[index]) { return index }
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
private func pump() {
|
||||
guard active == nil, !queue.isEmpty, let peripheral, let key, !session.isEmpty else { return }
|
||||
let index = Self.nextRequestIndex(methods: queue.map(\.method), paths: queue.map(\.path), priorityStreak: priorityStreak)
|
||||
active = queue.remove(at: index)
|
||||
guard let active else { return }
|
||||
priorityStreak = active.method == "GET" && !Self.backgroundRead(active.path) ? min(3, priorityStreak + 1) : 0
|
||||
requestStarted = ProcessInfo.processInfo.systemUptime
|
||||
receivedPackets = 0
|
||||
receivedWireBytes = 0
|
||||
counter += 1
|
||||
assembler = FrameAssembler()
|
||||
completedResponse = nil
|
||||
activeCancelled = false
|
||||
awaitingAck = false
|
||||
writeIndex = 0
|
||||
activeNotifications = Self.useNotifications(method: active.method, path: active.path, supported: supportsNotifications, fastReads: fastReads && !fastReadFallback)
|
||||
notificationCount = 0
|
||||
notificationBuffer = []
|
||||
activeReadStream = supportsReadStream && active.path != "/_bridge/health"
|
||||
onEvent?("Bluetooth request started: \(LoopbackServer.reportPath(active.path)), queued=\(queue.count), waited=\(String(format: "%.2f", requestStarted - active.enqueuedAt))s, response=\(activeNotifications ? "notifications" : activeReadStream ? "read stream" : "encrypted reads")")
|
||||
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(),
|
||||
phone: active.phone, 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
|
||||
if let previous {
|
||||
let outcome: String
|
||||
switch result {
|
||||
case .success(let response): outcome = "HTTP \(response.status), \(response.bodyData.count) bytes"
|
||||
case .failure: outcome = "failed"
|
||||
}
|
||||
let elapsed = max(0.001, ProcessInfo.processInfo.systemUptime - requestStarted)
|
||||
onEvent?("Bluetooth request finished: \(LoopbackServer.reportPath(previous.path)), \(outcome), packets=\(receivedPackets), wire=\(receivedWireBytes) bytes, rate=\(String(format: "%.1f", Double(receivedWireBytes) / elapsed / 1024)) KiB/s, transfer=\(String(format: "%.2f", ProcessInfo.processInfo.systemUptime - requestStarted))s")
|
||||
}
|
||||
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) {
|
||||
onEvent?("iOS Bluetooth state changed: \(central.state.rawValue)")
|
||||
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); onEvent?("Bluetooth service candidate discovered: RSSI=\(RSSI.intValue), candidates=\(devices.count)") }
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
onEvent?("Bluetooth link established; discovering Galaxy service")
|
||||
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 }
|
||||
disconnect(reason: "Bluetooth peer disconnected: \(error.map { LANTransport.failureCode($0) } ?? "no OS error supplied")")
|
||||
status = 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("StarPilot BT service was not found."); return
|
||||
}
|
||||
onEvent?("Bluetooth Galaxy service found; discovering characteristics")
|
||||
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
|
||||
}
|
||||
onEvent?("Bluetooth characteristics ready; reading handshake challenge")
|
||||
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 {
|
||||
if activeNotifications { onEvent?("Bluetooth notification window acknowledged: packets=\(notificationCount), complete=\(completedResponse != nil)") }
|
||||
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(),
|
||||
phone: PairingKeyStore.phone(for: self.keyText, name: UIDevice.current.name))
|
||||
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, let notify = self.notify, notify.properties.contains(.notify) {
|
||||
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 {
|
||||
receivedPackets += 1
|
||||
receivedWireBytes += data.count
|
||||
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"
|
||||
onEvent?("Bluetooth encrypted handshake completed")
|
||||
}
|
||||
|
||||
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 {
|
||||
supportsNotifications = false
|
||||
if activeNotifications && active != nil {
|
||||
failConnection("Bluetooth push subscription ended. Reconnect to check any pending setting change.")
|
||||
} else if !connected {
|
||||
do { try completeConnection() } catch { failConnection(error.localizedDescription) }
|
||||
}
|
||||
onEvent?("Bluetooth notifications unavailable; using encrypted reads.")
|
||||
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
|
||||
receivedPackets += 1
|
||||
receivedWireBytes += data.count
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?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>
|
||||
@@ -1,554 +0,0 @@
|
||||
import CarPlay
|
||||
import UIKit
|
||||
import CoreFoundation
|
||||
|
||||
@MainActor
|
||||
final class CarPlaySceneDelegate: NSObject, CPTemplateApplicationSceneDelegate, CPTabBarTemplateDelegate, CPSessionConfigurationDelegate {
|
||||
private final class GridAction: NSObject {
|
||||
var perform: @MainActor () -> Void
|
||||
var signature: String
|
||||
init(signature: String, perform: @escaping @MainActor () -> Void) {
|
||||
self.signature = signature; self.perform = perform
|
||||
}
|
||||
}
|
||||
private let gridActions = NSMapTable<CPGridButton, GridAction>.weakToStrongObjects()
|
||||
private final class WeakGrid {
|
||||
weak var page: CPGridTemplate?
|
||||
init(_ page: CPGridTemplate) { self.page = page }
|
||||
}
|
||||
private var sessionConfiguration: CPSessionConfiguration?
|
||||
private var controller: CPInterfaceController?
|
||||
private var timer: Timer?
|
||||
private var work: Task<Void, Never>?
|
||||
private var overview: CPGridTemplate?
|
||||
private var temperatures: CPGridTemplate?
|
||||
private var rates: CPGridTemplate?
|
||||
private var toggles: CPGridTemplate?
|
||||
private var catalog: [[String: Any]] = []
|
||||
private var values: [String: Any] = [:]
|
||||
private var valuesSession = ""
|
||||
private var valuesAt = Date.distantPast
|
||||
private var categoryPage = 0
|
||||
private var busy = false
|
||||
private var navigating = false
|
||||
private final class GridRefresh: NSObject {
|
||||
let perform: @MainActor () -> Void
|
||||
init(_ perform: @escaping @MainActor () -> Void) { self.perform = perform }
|
||||
}
|
||||
private let settingsRefresh = NSMapTable<CPGridTemplate, GridRefresh>.weakToStrongObjects()
|
||||
private let overflowParents = NSMapTable<CPTemplate, CPTemplate>.weakToStrongObjects()
|
||||
private let gridSizes = NSMapTable<CPGridTemplate, NSNumber>.weakToStrongObjects()
|
||||
private final class MetricPageState {
|
||||
let title: String
|
||||
let kind: String
|
||||
var index = 0
|
||||
init(title: String, kind: String) { self.title = title; self.kind = kind }
|
||||
}
|
||||
|
||||
func templateApplicationScene(_ scene: CPTemplateApplicationScene, didConnect interfaceController: CPInterfaceController) {
|
||||
controller = interfaceController
|
||||
sessionConfiguration = CPSessionConfiguration(delegate: self)
|
||||
overview = nil; temperatures = nil; rates = nil; toggles = nil
|
||||
let model = AppModel.shared
|
||||
model.setCarPlayActive(true)
|
||||
refreshTelemetry()
|
||||
catalog = localCatalogue()
|
||||
toggles = grid("Toggles", icon: "switch.2", buttons: categoryButtons())
|
||||
guard let overview, let temperatures, let rates, let toggles else { return }
|
||||
let tabs = CPTabBarTemplate(templates: [overview, temperatures, rates, toggles])
|
||||
tabs.delegate = self
|
||||
interfaceController.setRootTemplate(tabs, animated: false, completion: nil)
|
||||
showCategories()
|
||||
timer?.invalidate()
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in self?.refreshTelemetry() }
|
||||
}
|
||||
}
|
||||
|
||||
func templateApplicationScene(_ scene: CPTemplateApplicationScene, didDisconnectInterfaceController interfaceController: CPInterfaceController) {
|
||||
timer?.invalidate(); timer = nil
|
||||
work?.cancel(); work = nil
|
||||
controller = nil
|
||||
sessionConfiguration?.delegate = nil; sessionConfiguration = nil
|
||||
overview = nil; temperatures = nil; rates = nil; toggles = nil
|
||||
catalog = []; values = [:]; busy = false; categoryPage = 0; valuesSession = ""; valuesAt = .distantPast
|
||||
gridActions.removeAllObjects(); gridSizes.removeAllObjects(); overflowParents.removeAllObjects(); settingsRefresh.removeAllObjects(); navigating = false
|
||||
AppModel.shared.setCarPlayActive(false)
|
||||
}
|
||||
|
||||
func tabBarTemplate(_ tabBarTemplate: CPTabBarTemplate, didSelect selectedTemplate: CPTemplate) {
|
||||
if selectedTemplate === toggles { loadGalaxy() }
|
||||
}
|
||||
|
||||
private var carAppearance: UIUserInterfaceStyle {
|
||||
if let style = sessionConfiguration?.contentStyle {
|
||||
if style.contains(.dark) && !style.contains(.light) { return .dark }
|
||||
if style.contains(.light) && !style.contains(.dark) { return .light }
|
||||
}
|
||||
return controller?.carTraitCollection.userInterfaceStyle == .dark ? .dark : .light
|
||||
}
|
||||
|
||||
func sessionConfiguration(_ sessionConfiguration: CPSessionConfiguration, contentStyleChanged contentStyle: CPContentStyle) {
|
||||
let appearance: UIUserInterfaceStyle = contentStyle.contains(.dark) && !contentStyle.contains(.light) ? .dark :
|
||||
contentStyle.contains(.light) && !contentStyle.contains(.dark) ? .light : carAppearance
|
||||
let traits = UITraitCollection(userInterfaceStyle: appearance)
|
||||
let templates = controller?.templates ?? []
|
||||
var visited = Set<ObjectIdentifier>()
|
||||
for template in templates.flatMap({ ($0 as? CPTabBarTemplate)?.templates ?? [$0] }) {
|
||||
guard let grid = template as? CPGridTemplate, visited.insert(ObjectIdentifier(grid)).inserted else { continue }
|
||||
for button in grid.gridButtons {
|
||||
if #available(iOS 26.0, *), let asset = button.image.imageAsset { button.updateImage(asset.image(with: traits)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func pushTemplate(_ template: CPTemplate, animated: Bool, completion: ((Bool, Error?) -> Void)?) {
|
||||
guard let controller, !navigating else { completion?(false, nil); return }
|
||||
navigating = true
|
||||
let finished: (Bool, Error?) -> Void = { [weak self, weak controller] success, error in
|
||||
guard let self, let controller, self.controller === controller else { return }
|
||||
self.navigating = false
|
||||
completion?(success, error)
|
||||
if !success { self.notice(error?.localizedDescription ?? "This page could not be opened.") }
|
||||
}
|
||||
// A tab container also occupies a hierarchy level. Reserve that level before pushing.
|
||||
if controller.templates.count >= 4, let parent = controller.topTemplate {
|
||||
controller.popTemplate(animated: false) { [weak self, weak controller] success, error in
|
||||
guard let self, let controller, self.controller === controller else { return }
|
||||
guard success else { finished(false, error); return }
|
||||
self.overflowParents.setObject(parent, forKey: template)
|
||||
if let page = template as? CPBarButtonProviding {
|
||||
page.backButton = CPBarButton(image: UIImage(systemName: "chevron.left")!) { [weak self] _ in
|
||||
self?.popTemplate(animated: true, completion: nil)
|
||||
}
|
||||
}
|
||||
controller.pushTemplate(template, animated: animated, completion: finished)
|
||||
}
|
||||
} else {
|
||||
controller.pushTemplate(template, animated: animated, completion: finished)
|
||||
}
|
||||
}
|
||||
|
||||
private func popTemplate(animated: Bool, completion: ((Bool, Error?) -> Void)?) {
|
||||
guard let controller, !navigating else { completion?(false, nil); return }
|
||||
let top = controller.topTemplate
|
||||
let parent = top.flatMap { overflowParents.object(forKey: $0) }
|
||||
navigating = true
|
||||
controller.popTemplate(animated: animated) { [weak self, weak controller] success, error in
|
||||
guard let self, let controller, self.controller === controller else { return }
|
||||
guard success else { self.navigating = false; completion?(false, error); return }
|
||||
if let top { self.overflowParents.removeObject(forKey: top) }
|
||||
if let parent {
|
||||
controller.pushTemplate(parent, animated: false) { [weak self] restored, error in
|
||||
self?.navigating = false; completion?(restored, error)
|
||||
}
|
||||
} else {
|
||||
self.navigating = false; completion?(true, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func paddedButtons(_ buttons: [CPGridButton], capacity: Int = 8) -> [CPGridButton] {
|
||||
var result = Array(buttons.prefix(capacity))
|
||||
while result.count < capacity {
|
||||
let empty = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in }
|
||||
let action = GridAction(signature: "empty", perform: {})
|
||||
let spacer = CPGridButton(titleVariants: [" "], image: empty) { _ in action.perform() }
|
||||
gridActions.setObject(action, forKey: spacer)
|
||||
spacer.isEnabled = false
|
||||
result.append(spacer)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private func makeGrid(title: String?, gridButtons: [CPGridButton], compact: Bool = false) -> CPGridTemplate {
|
||||
let capacity = compact ? 4 : 8
|
||||
let page = CPGridTemplate(title: title, gridButtons: paddedButtons(gridButtons, capacity: capacity))
|
||||
gridSizes.setObject(NSNumber(value: capacity), forKey: page)
|
||||
return page
|
||||
}
|
||||
|
||||
private func grid(_ title: String, icon: String, buttons: [CPGridButton]) -> CPGridTemplate {
|
||||
precondition(!buttons.isEmpty)
|
||||
let template = makeGrid(title: title, gridButtons: buttons)
|
||||
template.tabTitle = title
|
||||
template.tabImage = UIImage(systemName: icon)
|
||||
return template
|
||||
}
|
||||
|
||||
private func button(_ title: String, icon: String, value: String? = nil, action: @escaping @MainActor () -> Void = {}) -> CPGridButton {
|
||||
let configuration = UIImage.SymbolConfiguration(pointSize: 32, weight: .regular)
|
||||
let symbol = UIImage(systemName: icon, withConfiguration: configuration) ?? UIImage(systemName: "circle")!
|
||||
let image: UIImage
|
||||
if let value {
|
||||
let format = UIGraphicsImageRendererFormat()
|
||||
format.scale = controller?.carTraitCollection.displayScale ?? 2
|
||||
let text = value.replacingOccurrences(of: " °C", with: "°").replacingOccurrences(of: " FPS", with: "")
|
||||
let asset = UIImageAsset()
|
||||
for (style, color) in [(UIUserInterfaceStyle.light, UIColor.black), (.dark, UIColor.white)] {
|
||||
let rendered = UIGraphicsImageRenderer(size: CGSize(width: 72, height: 72), format: format).image { _ in
|
||||
if value == "On" || value == "Off" {
|
||||
let on = value == "On"
|
||||
(on ? UIColor.systemGreen : (style == .dark ? UIColor.darkGray : UIColor.systemGray)).setFill()
|
||||
UIBezierPath(roundedRect: CGRect(x: 3, y: 7, width: 66, height: 36), cornerRadius: 18).fill()
|
||||
UIColor.white.setFill()
|
||||
UIBezierPath(ovalIn: CGRect(x: on ? 36 : 6, y: 10, width: 30, height: 30)).fill()
|
||||
} else {
|
||||
symbol.withTintColor(color, renderingMode: .alwaysOriginal).draw(in: CGRect(x: 22, y: 0, width: 28, height: 28))
|
||||
}
|
||||
let paragraph = NSMutableParagraphStyle(); paragraph.alignment = .center
|
||||
let size: CGFloat = text.count <= 6 ? 24 : text.count <= 10 ? 18 : 14
|
||||
(text as NSString).draw(in: CGRect(x: 0, y: value == "On" || value == "Off" ? 47 : 36, width: 72, height: 25), withAttributes: [
|
||||
.font: UIFont.monospacedDigitSystemFont(ofSize: size, weight: .semibold),
|
||||
.foregroundColor: color, .paragraphStyle: paragraph
|
||||
])
|
||||
}.withRenderingMode(.alwaysOriginal)
|
||||
asset.register(rendered, with: UITraitCollection(traitsFrom: [
|
||||
UITraitCollection(userInterfaceStyle: style), UITraitCollection(displayScale: format.scale)
|
||||
]))
|
||||
}
|
||||
image = asset.image(with: UITraitCollection(traitsFrom: [
|
||||
UITraitCollection(userInterfaceStyle: carAppearance), UITraitCollection(displayScale: format.scale)
|
||||
]))
|
||||
} else { image = symbol.withRenderingMode(.alwaysTemplate) }
|
||||
let label = title
|
||||
let state = GridAction(signature: "\(title)|\(icon)|\(value ?? "")", perform: action)
|
||||
let result = CPGridButton(titleVariants: [label, compactCaption(label)], image: image) { _ in state.perform() }
|
||||
gridActions.setObject(state, forKey: result)
|
||||
return result
|
||||
}
|
||||
|
||||
private func compactCaption(_ label: String) -> String {
|
||||
label.replacingOccurrences(of: "Advanced ", with: "Adv. ")
|
||||
.replacingOccurrences(of: "Longitudinal", with: "Speed")
|
||||
.replacingOccurrences(of: "Lateral", with: "Steering")
|
||||
.replacingOccurrences(of: "Acceleration", with: "Accel.")
|
||||
.replacingOccurrences(of: "Deceleration", with: "Braking")
|
||||
.replacingOccurrences(of: "Conditional ", with: "")
|
||||
.replacingOccurrences(of: "Controller", with: "Control")
|
||||
}
|
||||
|
||||
private func updateGrid(_ page: CPGridTemplate, buttons rawButtons: [CPGridButton]) {
|
||||
precondition(!rawButtons.isEmpty)
|
||||
let buttons = paddedButtons(rawButtons, capacity: gridSizes.object(forKey: page)?.intValue ?? 8)
|
||||
if #available(iOS 26.0, *), page.gridButtons.count == buttons.count {
|
||||
for (existing, replacement) in zip(page.gridButtons, buttons) {
|
||||
guard let current = gridActions.object(forKey: existing),
|
||||
let next = gridActions.object(forKey: replacement) else {
|
||||
page.updateGridButtons(buttons)
|
||||
return
|
||||
}
|
||||
current.perform = next.perform
|
||||
existing.isEnabled = replacement.isEnabled
|
||||
if current.signature != next.signature {
|
||||
existing.updateTitleVariants(replacement.titleVariants)
|
||||
existing.updateImage(replacement.image)
|
||||
current.signature = next.signature
|
||||
}
|
||||
}
|
||||
} else {
|
||||
page.updateGridButtons(buttons)
|
||||
}
|
||||
}
|
||||
|
||||
private func telemetryGrid(_ existing: CPGridTemplate?, title: String, icon: String,
|
||||
buttons: [CPGridButton]) -> CPGridTemplate {
|
||||
if let existing { updateGrid(existing, buttons: buttons); return existing }
|
||||
return grid(title, icon: icon, buttons: buttons)
|
||||
}
|
||||
|
||||
private func external(_ metric: DiagnosticMetric) -> Bool {
|
||||
let name = metric.name.lowercased()
|
||||
return name.contains("external gpu") || name.contains("chestnut") || name.hasPrefix("sensor: amdgpu")
|
||||
}
|
||||
|
||||
private func thermalGroup(_ metric: DiagnosticMetric) -> String {
|
||||
let name = metric.name.lowercased()
|
||||
if external(metric) { return "External GPU" }
|
||||
if name.hasPrefix("sensor:") { return "Other 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("intake") || name.contains("exhaust") { return "Cooling" }
|
||||
if name.contains("pmic") { return "Power" }
|
||||
if name.contains("modem") || name.contains("gnss") { return "Connectivity" }
|
||||
return "Other sensors"
|
||||
}
|
||||
|
||||
private func thermalLabel(_ group: String) -> String {
|
||||
switch group {
|
||||
case "Processors": return "CPU / DSP"
|
||||
case "Onboard GPU": return "GPU"
|
||||
case "Connectivity": return "Radios"
|
||||
case "Other sensors": return "Sensors"
|
||||
default: return group
|
||||
}
|
||||
}
|
||||
|
||||
private func thermalIcon(_ group: String) -> String {
|
||||
switch group {
|
||||
case "Processors", "Onboard GPU", "External GPU": return "cpu"
|
||||
case "Memory": return "memorychip"
|
||||
case "Cooling": return "fan"
|
||||
case "Power": return "bolt"
|
||||
case "Connectivity": return "antenna.radiowaves.left.and.right"
|
||||
default: return "thermometer.medium"
|
||||
}
|
||||
}
|
||||
|
||||
private func maximum(_ metrics: [DiagnosticMetric]) -> String {
|
||||
guard let value = metrics.compactMap(\.value).filter(\.isFinite).max() else { return "—" }
|
||||
return String(format: "%.1f °C", value)
|
||||
}
|
||||
|
||||
private func refreshTelemetry() {
|
||||
let model = AppModel.shared
|
||||
let system = model.diagnostics.fresh ? model.diagnostics.system ?? [:] : [:]
|
||||
let memory = system["memory"] as? [String: Any] ?? [:]
|
||||
let storage = system["storage"] as? [String: Any] ?? [:]
|
||||
func value(_ source: [String: Any], _ key: String, _ unit: String) -> String {
|
||||
guard let number = source[key] as? NSNumber, number.doubleValue.isFinite else { return "—" }
|
||||
return String(format: "%.1f %@", number.doubleValue, unit)
|
||||
}
|
||||
overview = telemetryGrid(overview, title: "Overview", icon: "sparkles", buttons: [
|
||||
button(model.transport.label, icon: "antenna.radiowaves.left.and.right"),
|
||||
button("CPU", icon: "cpu", value: value(system, "cpuPercent", "%")),
|
||||
button("Memory", icon: "memorychip", value: value(memory, "percent", "%")),
|
||||
button("Storage used", icon: "internaldrive", value: value(storage, "usedGiB", "GiB")),
|
||||
button("Uptime", icon: "clock", value: value(system, "uptimeSeconds", "s")),
|
||||
button("Processes", icon: "list.bullet", value: value(system, "processCount", ""))
|
||||
])
|
||||
let cores = system["cores"] as? [[String: Any]] ?? []
|
||||
rates = telemetryGrid(rates, title: "CPU", icon: "cpu", buttons: cores.isEmpty ? [button("Waiting for CPU readings", icon: "cpu")] : cores.prefix(8).map {
|
||||
button($0["name"] as? String ?? "CPU", icon: "cpu", value: value($0, "percent", "%"))
|
||||
})
|
||||
temperatures = telemetryGrid(temperatures, title: "Memory", icon: "memorychip", buttons: [
|
||||
button("Used", icon: "memorychip", value: value(memory, "usedMiB", "MiB")),
|
||||
button("Available", icon: "memorychip", value: value(memory, "availableMiB", "MiB")),
|
||||
button("Total", icon: "memorychip", value: value(memory, "totalMiB", "MiB")),
|
||||
button("Storage total", icon: "internaldrive", value: value(storage, "totalGiB", "GiB"))
|
||||
])
|
||||
}
|
||||
|
||||
private func rateGroup(_ metric: DiagnosticMetric) -> String {
|
||||
let name = metric.name.lowercased()
|
||||
if external(metric) { return "external" }
|
||||
if name.contains("camera") { return "cameras" }
|
||||
if name.contains("model") || name.contains("plan") { return "models" }
|
||||
if name.contains("carstate") || name.contains("carcontrol") || name.contains("selfdrive") { return "driving" }
|
||||
if name == "ui" { return "display" }
|
||||
return "other"
|
||||
}
|
||||
|
||||
private func showMetrics(_ title: String, kind: String) {
|
||||
guard controller != nil else { return }
|
||||
let page = makeGrid(title: title, gridButtons: [button("Loading readings…", icon: "hourglass")])
|
||||
page.userInfo = MetricPageState(title: title, kind: kind)
|
||||
updateMetrics(page)
|
||||
pushTemplate(page, animated: true, completion: nil)
|
||||
}
|
||||
|
||||
private func updateMetrics(_ page: CPGridTemplate) {
|
||||
guard let state = page.userInfo as? MetricPageState else { return }
|
||||
let diagnostics = AppModel.shared.diagnostics
|
||||
guard diagnostics.fresh, let sample = diagnostics.snapshot else {
|
||||
updateGrid(page, buttons: [button("Telemetry unavailable", icon: "exclamationmark.triangle") { [weak self] in self?.notice(diagnostics.status) }])
|
||||
return
|
||||
}
|
||||
let readings = sample.temperatures.filter { thermalGroup($0) == state.kind } + sample.rates.filter { rateGroup($0) == state.kind }
|
||||
let count = max(1, (readings.count + 7) / 8)
|
||||
state.index = min(state.index, count - 1)
|
||||
var buttons = readings.dropFirst(state.index * 8).prefix(8).map { button($0.name, icon: "gauge", value: $0.display) }
|
||||
if buttons.isEmpty { buttons = [button("No readings available", icon: "questionmark.circle")] }
|
||||
paging(page, index: state.index, count: count) { [weak self, weak page] index in
|
||||
guard let self, let page else { return }; state.index = index; self.updateMetrics(page)
|
||||
}
|
||||
page.updateTitle(count > 1 ? "\(state.title) · \(state.index + 1)/\(count)" : state.title)
|
||||
updateGrid(page, buttons: buttons)
|
||||
}
|
||||
|
||||
private final class SettingsPageState {
|
||||
let name: String
|
||||
var snapshot: [String: Any] = [:]
|
||||
var session = ""
|
||||
var index = 0
|
||||
init(_ name: String) { self.name = name }
|
||||
}
|
||||
private var session: String {
|
||||
let model = AppModel.shared
|
||||
return model.transport.usesLAN ? "lan-" + model.lan.generation : "ble-" + model.bluetooth.sessionIdentifier
|
||||
}
|
||||
private func request(_ path: String, payload: [String: Any]? = nil) async throws -> [String: Any] {
|
||||
let original = session
|
||||
let response = try await AppModel.shared.transport.request(path: path, method: payload == nil ? "GET" : "POST",
|
||||
headers: payload == nil ? [:] : ["Content-Type": "application/json"],
|
||||
body: try payload.map { try JSONSerialization.data(withJSONObject: $0) } ?? Data())
|
||||
try Task.checkCancellation()
|
||||
guard original == session else { throw BridgeError.message("Connection changed. Refresh the page.") }
|
||||
let data = (try? JSONSerialization.jsonObject(with: response.bodyData)) as? [String: Any] ?? [:]
|
||||
guard response.status == 200 else {
|
||||
throw BridgeError.message(data["error"] as? String ?? "Galaxy request failed (HTTP \(response.status)).")
|
||||
}
|
||||
return data
|
||||
}
|
||||
private func localCatalogue() -> [[String: Any]] { [] }
|
||||
private func categoryButtons() -> [CPGridButton] {
|
||||
[button("Open toggles", icon: "switch.2") { [weak self] in self?.loadGalaxy() }]
|
||||
}
|
||||
private func showCategories() { loadGalaxy() }
|
||||
private func loadGalaxy() {
|
||||
guard let toggles else { return }
|
||||
if toggles.userInfo == nil { toggles.userInfo = SettingsPageState("hub") }
|
||||
loadSettings(toggles)
|
||||
}
|
||||
private func openSettings(_ name: String, title: String) {
|
||||
let page = makeGrid(title: title, gridButtons: [button("Loading…", icon: "hourglass")])
|
||||
page.userInfo = SettingsPageState(name)
|
||||
pushTemplate(page, animated: true) { [weak self, weak page] success, _ in
|
||||
if success, let page { self?.loadSettings(page) }
|
||||
}
|
||||
}
|
||||
private func loadSettings(_ page: CPGridTemplate) {
|
||||
guard let state = page.userInfo as? SettingsPageState, !busy else { return }
|
||||
work?.cancel()
|
||||
work = Task { [weak self, weak page] in
|
||||
guard let self, let page else { return }
|
||||
do {
|
||||
let name = state.name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/")))!
|
||||
state.snapshot = try await self.request("/api/settings/pages/" + name)
|
||||
state.session = self.session
|
||||
self.drawSettings(page)
|
||||
} catch {
|
||||
if !Task.isCancelled {
|
||||
self.updateGrid(page, buttons: [self.button("Retry", icon: "arrow.clockwise") { [weak self, weak page] in
|
||||
if let page { self?.loadSettings(page) }
|
||||
}])
|
||||
self.notice(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private func drawSettings(_ page: CPGridTemplate) {
|
||||
guard let state = page.userInfo as? SettingsPageState else { return }
|
||||
let rows = state.snapshot["rows"] as? [[String: Any]] ?? []
|
||||
let count = max(1, (rows.count + 7) / 8)
|
||||
state.index = min(state.index, count - 1)
|
||||
var buttons: [CPGridButton] = []
|
||||
for index in (state.index * 8)..<min(rows.count, (state.index + 1) * 8) {
|
||||
let row = rows[index]
|
||||
let child = row["page"] as? String ?? ""
|
||||
let value = row["value"].map { String(describing: $0) } ?? ""
|
||||
let choices = row["choices"] as? [String] ?? []
|
||||
let icon = !child.isEmpty ? "folder" : choices.contains("On") && choices.contains("Off") ?
|
||||
(value == "On" ? "switch.2" : "switch.2") : "slider.horizontal.3"
|
||||
let tile = button(row["label"] as? String ?? "Setting", icon: icon, value: child.isEmpty ? value : nil) { [weak self, weak page] in
|
||||
guard let self, let page else { return }
|
||||
guard state.session == self.session else { self.loadSettings(page); return }
|
||||
if !child.isEmpty { self.openSettings(child, title: row["label"] as? String ?? "Toggles") }
|
||||
else { self.editSetting(page, index: index, row: row) }
|
||||
}
|
||||
tile.isEnabled = row["available"] as? Bool == true && (!child.isEmpty || row["action"] as? Bool == true) && !busy
|
||||
buttons.append(tile)
|
||||
}
|
||||
updateGrid(page, buttons: buttons.isEmpty ? [button("No settings available", icon: "info.circle")] : buttons)
|
||||
var navigation: [CPBarButton] = []
|
||||
if state.index > 0 {
|
||||
navigation.append(CPBarButton(image: UIImage(systemName: "chevron.left")!) { [weak self, weak page] _ in
|
||||
guard let page else { return }; state.index -= 1; self?.drawSettings(page)
|
||||
})
|
||||
}
|
||||
if state.index + 1 < count {
|
||||
navigation.append(CPBarButton(image: UIImage(systemName: "chevron.right")!) { [weak self, weak page] _ in
|
||||
guard let page else { return }; state.index += 1; self?.drawSettings(page)
|
||||
})
|
||||
}
|
||||
page.trailingNavigationBarButtons = navigation
|
||||
}
|
||||
private func editSetting(_ parent: CPGridTemplate, index: Int, row: [String: Any]) {
|
||||
let choices = row["choices"] as? [String] ?? []
|
||||
if choices.count == 2, choices.contains("On"), choices.contains("Off") {
|
||||
preview(parent, index: index, selection: row["value"] as? String == "On" ? "Off" : "On")
|
||||
return
|
||||
}
|
||||
let editor = makeGrid(title: row["label"] as? String, gridButtons: [button("Loading…", icon: "hourglass")])
|
||||
var buttons: [CPGridButton] = []
|
||||
if !choices.isEmpty {
|
||||
var choicePage = 0
|
||||
func redraw() {
|
||||
let count = max(1, (choices.count + 7) / 8)
|
||||
let start = choicePage * 8
|
||||
let tiles = choices[start..<min(start + 8, choices.count)].map { choice in
|
||||
button(choice, icon: String(describing: row["value"] ?? "") == choice ? "checkmark.circle.fill" : "circle") { [weak self] in
|
||||
self?.preview(parent, index: index, selection: choice)
|
||||
}
|
||||
}
|
||||
updateGrid(editor, buttons: tiles)
|
||||
paging(editor, index: choicePage, count: count) { next in choicePage = next; redraw() }
|
||||
}
|
||||
redraw()
|
||||
pushTemplate(editor, animated: true, completion: nil)
|
||||
return
|
||||
} else if (row["step"] as? NSNumber)?.doubleValue ?? 0 > 0 {
|
||||
buttons = [button("Decrease", icon: "minus.circle", value: String(describing: row["value"] ?? "")) { [weak self] in self?.preview(parent, index: index, direction: -1) },
|
||||
button("Increase", icon: "plus.circle", value: String(describing: row["value"] ?? "")) { [weak self] in self?.preview(parent, index: index, direction: 1) }]
|
||||
} else {
|
||||
buttons = [button("Continue", icon: "checkmark.circle") { [weak self] in self?.preview(parent, index: index, direction: 0) }]
|
||||
}
|
||||
updateGrid(editor, buttons: buttons)
|
||||
pushTemplate(editor, animated: true, completion: nil)
|
||||
}
|
||||
private func preview(_ page: CPGridTemplate, index: Int, selection: String? = nil, direction: Int = 0) {
|
||||
guard !busy, let state = page.userInfo as? SettingsPageState, state.session == session,
|
||||
let view = state.snapshot["view"] as? String else { loadSettings(page); return }
|
||||
busy = true
|
||||
let original = session
|
||||
Task { [weak self, weak page] in
|
||||
guard let self, let page else { return }
|
||||
defer { self.busy = false }
|
||||
do {
|
||||
var payload: [String: Any] = ["view": view, "row": index, "direction": direction]
|
||||
if let selection { payload["value"] = selection }
|
||||
let pending = try await self.request("/api/settings/preview", payload: payload)
|
||||
guard let intent = pending["intent"] as? String else { throw BridgeError.message("Refresh settings and try again.") }
|
||||
let confirm = CPAlertAction(title: "Save", style: .default) { [weak self, weak page] _ in
|
||||
guard let self, let page else { return }
|
||||
self.controller?.dismissTemplate(animated: true) { _, _ in
|
||||
guard original == self.session else { self.notice("Connection changed. Refresh settings."); return }
|
||||
self.commit(intent, page: page)
|
||||
}
|
||||
}
|
||||
let cancel = CPAlertAction(title: "Cancel", style: .cancel) { [weak self] _ in self?.controller?.dismissTemplate(animated: true, completion: nil) }
|
||||
self.controller?.presentTemplate(CPAlertTemplate(titleVariants: [pending["question"] as? String ?? "Save this preference?"], actions: [cancel, confirm]), animated: true, completion: nil)
|
||||
} catch { self.notice(error.localizedDescription); self.busy = false; self.loadSettings(page) }
|
||||
}
|
||||
}
|
||||
private func commit(_ intent: String, page: CPGridTemplate) {
|
||||
guard !busy else { return }
|
||||
busy = true
|
||||
Task { [weak self, weak page] in
|
||||
guard let self, let page else { return }
|
||||
do {
|
||||
let result = try await self.request("/api/settings/confirm", payload: ["intent": intent, "confirmed": true])
|
||||
if result["saved"] as? Bool != true { self.notice("Save could not be confirmed. Check the current value.") }
|
||||
} catch { self.notice(error.localizedDescription) }
|
||||
self.busy = false
|
||||
if self.controller?.topTemplate !== page {
|
||||
self.popTemplate(animated: true) { [weak self, weak page] _, _ in
|
||||
if let page { self?.loadSettings(page) }
|
||||
}
|
||||
} else { self.loadSettings(page) }
|
||||
}
|
||||
}
|
||||
private func paging(_ page: CPGridTemplate, index: Int, count: Int, change: @escaping @MainActor (Int) -> Void) {
|
||||
var items: [CPBarButton] = []
|
||||
if index > 0 { items.append(CPBarButton(image: UIImage(systemName: "chevron.left")!) { _ in change(index - 1) }) }
|
||||
if index + 1 < count { items.append(CPBarButton(image: UIImage(systemName: "chevron.right")!) { _ in change(index + 1) }) }
|
||||
page.trailingNavigationBarButtons = items
|
||||
}
|
||||
|
||||
private func notice(_ message: String) {
|
||||
guard controller?.presentedTemplate == nil else { return }
|
||||
let action = CPAlertAction(title: "OK", style: .cancel) { [weak self] _ in self?.controller?.dismissTemplate(animated: true, completion: nil) }
|
||||
controller?.presentTemplate(CPAlertTemplate(titleVariants: [String(message.prefix(240))], actions: [action]), animated: true, completion: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import CoreBluetooth
|
||||
|
||||
/// What comma hands a phone when its pairing window is open (Settings → Bluetooth → Pair phone on comma).
|
||||
struct ClaimResult: Equatable {
|
||||
let key: String
|
||||
let id: String?
|
||||
let adapterAddress: String
|
||||
let adapterName: String
|
||||
}
|
||||
|
||||
/// Byte layout: galaxy_bluetooth/README.md, "Pairing a phone". The phone sends a P-256 public key and gets its own
|
||||
/// key back, sealed under an ECDH-derived key, so nothing a nearby listener can read ever contains the key.
|
||||
enum ClaimCrypto {
|
||||
static let requestMagic = Data("GCL1".utf8)
|
||||
static let replyMagic = Data("GCR1".utf8)
|
||||
static let info = Data("galaxy-claim-v1".utf8)
|
||||
static let aad = Data("galaxy-claim-v1/reply".utf8)
|
||||
static let point = 65
|
||||
|
||||
static func request(publicKey: P256.KeyAgreement.PublicKey, name: String) -> Data {
|
||||
requestMagic + publicKey.x963Representation + Data(String(name.prefix(40)).utf8)
|
||||
}
|
||||
|
||||
static func derive(_ privateKey: P256.KeyAgreement.PrivateKey, peer: Data, challenge: Data) throws -> SymmetricKey {
|
||||
let secret = try privateKey.sharedSecretFromKeyAgreement(with: P256.KeyAgreement.PublicKey(x963Representation: peer))
|
||||
return secret.hkdfDerivedSymmetricKey(using: SHA256.self, salt: challenge, sharedInfo: info, outputByteCount: 32)
|
||||
}
|
||||
|
||||
static func open(_ reply: Data, privateKey: P256.KeyAgreement.PrivateKey, challenge: Data) throws -> ClaimResult {
|
||||
let reply = Data(reply)
|
||||
guard reply.count > 4 + point + 12 + 16, reply.prefix(4) == replyMagic else {
|
||||
throw BridgeError.message("comma sent an unexpected reply.")
|
||||
}
|
||||
let key = try derive(privateKey, peer: reply.subdata(in: 4..<(4 + point)), challenge: challenge)
|
||||
let nonce = try AES.GCM.Nonce(data: reply.subdata(in: (4 + point)..<(4 + point + 12)))
|
||||
let rest = reply.dropFirst(4 + point + 12)
|
||||
let box = try AES.GCM.SealedBox(nonce: nonce, ciphertext: rest.dropLast(16), tag: rest.suffix(16))
|
||||
return try parse(try AES.GCM.open(box, using: key, authenticating: aad))
|
||||
}
|
||||
|
||||
static func parse(_ json: Data) throws -> ClaimResult {
|
||||
guard let value = try JSONSerialization.jsonObject(with: json) as? [String: Any],
|
||||
let key = value["key"] as? String, key.utf8.count == 64,
|
||||
key.utf8.allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }) else {
|
||||
throw BridgeError.message("comma sent an unexpected pairing key.")
|
||||
}
|
||||
let address = (value["adapterAddress"] as? String) ?? ""
|
||||
return ClaimResult(key: key.lowercased(), id: PairingCode.validID(value["id"] as? String),
|
||||
adapterAddress: address.range(of: "^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$", options: .regularExpression) != nil ? address.uppercased() : "",
|
||||
adapterName: String(((value["adapterName"] as? String) ?? "").prefix(80)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-shot Bluetooth connection that asks the comma with its pairing window open for a key.
|
||||
/// It is separate from `BluetoothTransport` so the normal encrypted connection code is untouched.
|
||||
@MainActor
|
||||
final class ClaimTransport: NSObject, @preconcurrency CBCentralManagerDelegate, @preconcurrency CBPeripheralDelegate {
|
||||
struct Outcome {
|
||||
let result: ClaimResult
|
||||
let deviceID: UUID
|
||||
}
|
||||
|
||||
var onEvent: ((String) -> Void)?
|
||||
private var central: CBCentralManager?
|
||||
private var peripheral: CBPeripheral?
|
||||
private var rx: CBCharacteristic?
|
||||
private var tx: CBCharacteristic?
|
||||
private var continuation: CheckedContinuation<Outcome, Error>?
|
||||
private var privateKey = P256.KeyAgreement.PrivateKey()
|
||||
private var name = ""
|
||||
private var challenge = Data()
|
||||
private var outgoing: [Data] = []
|
||||
private var writeIndex = 0
|
||||
private var assembler = FrameAssembler()
|
||||
private var claimed: ClaimResult?
|
||||
private var handingOff = false
|
||||
private var timeout: Task<Void, Never>?
|
||||
|
||||
func claim(name: String) async throws -> Outcome {
|
||||
guard continuation == nil else { throw BridgeError.message("Pairing is already in progress.") }
|
||||
self.name = name
|
||||
challenge = Data()
|
||||
outgoing = []
|
||||
writeIndex = 0
|
||||
assembler = FrameAssembler()
|
||||
claimed = nil
|
||||
handingOff = false
|
||||
onEvent?("Phone pairing started")
|
||||
privateKey = P256.KeyAgreement.PrivateKey()
|
||||
return try await withCheckedThrowingContinuation { continuation in
|
||||
self.continuation = continuation
|
||||
central = CBCentralManager(delegate: self, queue: .main)
|
||||
timeout = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 30_000_000_000)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.fail("comma didn’t answer. On comma open Settings → Bluetooth → Pair phone, then try again.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
guard continuation != nil else { return }
|
||||
onEvent?("Phone pairing cancelled")
|
||||
finish(.failure(CancellationError()))
|
||||
}
|
||||
|
||||
private func fail(_ message: String) {
|
||||
onEvent?("Phone pairing failed: " + message)
|
||||
finish(.failure(BridgeError.message(message)))
|
||||
}
|
||||
|
||||
private func finish(_ result: Result<Outcome, Error>) {
|
||||
guard let continuation else { return }
|
||||
self.continuation = nil
|
||||
timeout?.cancel()
|
||||
central?.stopScan()
|
||||
if let peripheral, peripheral.state != .disconnected { central?.cancelPeripheralConnection(peripheral) }
|
||||
peripheral = nil; rx = nil; tx = nil; central = nil
|
||||
continuation.resume(with: result)
|
||||
}
|
||||
|
||||
func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
||||
guard central === self.central, continuation != nil else { return }
|
||||
switch central.state {
|
||||
case .poweredOn: central.scanForPeripherals(withServices: [CBUUID(string: Wire.service)], options: nil)
|
||||
case .unauthorized: fail("Allow Bluetooth access in iPhone Settings.")
|
||||
case .poweredOff: fail("Turn on Bluetooth to pair with comma.")
|
||||
case .unknown, .resetting: break
|
||||
default: fail("Bluetooth is unavailable.")
|
||||
}
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
|
||||
advertisementData: [String: Any], rssi RSSI: NSNumber) {
|
||||
guard central === self.central, continuation != nil, self.peripheral == nil else { return }
|
||||
onEvent?("Phone pairing found comma; connecting")
|
||||
central.stopScan()
|
||||
self.peripheral = peripheral
|
||||
peripheral.delegate = self
|
||||
central.connect(peripheral, options: nil)
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
||||
guard central === self.central, peripheral == self.peripheral else { return }
|
||||
onEvent?("Phone pairing connected; discovering service")
|
||||
peripheral.discoverServices([CBUUID(string: Wire.service)])
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
|
||||
guard central === self.central, peripheral == self.peripheral else { return }
|
||||
fail(error?.localizedDescription ?? "Could not connect to comma.")
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
|
||||
guard central === self.central, peripheral == self.peripheral, continuation != nil else { return }
|
||||
if handingOff, let claimed {
|
||||
onEvent?("Phone pairing complete; starting encrypted connection")
|
||||
finish(.success(Outcome(result: claimed, deviceID: peripheral.identifier)))
|
||||
} else {
|
||||
fail(error?.localizedDescription ?? "comma disconnected.")
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
fail("Galaxy Bluetooth service was not found."); return
|
||||
}
|
||||
peripheral.discoverCharacteristics([CBUUID(string: Wire.rx), CBUUID(string: Wire.tx), CBUUID(string: Wire.info)], for: service)
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
rx = service.characteristics?.first { $0.uuid == CBUUID(string: Wire.rx) }
|
||||
tx = service.characteristics?.first { $0.uuid == CBUUID(string: Wire.tx) }
|
||||
guard error == nil, rx != nil, tx != nil,
|
||||
let info = service.characteristics?.first(where: { $0.uuid == CBUUID(string: Wire.info) }) else {
|
||||
fail("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) else { return }
|
||||
if let error { fail(error.localizedDescription); return }
|
||||
if claimed != nil {
|
||||
// Release this connection before the normal transport connects to the same comma.
|
||||
handingOff = true
|
||||
onEvent?("Phone pairing key received; closing setup connection")
|
||||
central?.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
writeIndex += 1
|
||||
if writeIndex < outgoing.count, let rx { peripheral.writeValue(outgoing[writeIndex], for: rx, type: .withResponse) }
|
||||
else if let tx { peripheral.readValue(for: tx) }
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard peripheral == self.peripheral else { return }
|
||||
if let error { fail(error.localizedDescription); return }
|
||||
guard let data = characteristic.value else { fail("Empty Bluetooth response."); return }
|
||||
if characteristic.uuid == CBUUID(string: Wire.info) {
|
||||
guard data.count == 17, data.first == 1, let rx else { fail("Unsupported bridge protocol."); return }
|
||||
challenge = Data(data.dropFirst())
|
||||
let body = ClaimCrypto.request(publicKey: privateKey.publicKey, name: name)
|
||||
outgoing = Wire.packets(Wire.uint32(UInt32(body.count)) + body,
|
||||
size: min(180, peripheral.maximumWriteValueLength(for: .withoutResponse)))
|
||||
writeIndex = 0
|
||||
assembler = FrameAssembler()
|
||||
peripheral.writeValue(outgoing[0], for: rx, type: .withResponse)
|
||||
return
|
||||
}
|
||||
guard characteristic.uuid == CBUUID(string: Wire.tx), let tx, let rx else { return }
|
||||
if data == Data([0]) {
|
||||
// Comma is still working on its answer.
|
||||
Task { @MainActor [weak self, weak peripheral] in
|
||||
try? await Task.sleep(nanoseconds: 75_000_000)
|
||||
guard let self, let peripheral, peripheral == self.peripheral, self.continuation != nil else { return }
|
||||
peripheral.readValue(for: tx)
|
||||
}
|
||||
return
|
||||
}
|
||||
do {
|
||||
if let reply = try assembler.append(data) {
|
||||
claimed = try ClaimCrypto.open(reply, privateKey: privateKey, challenge: challenge)
|
||||
peripheral.writeValue(Data([2]) + data.subdata(in: 1..<5), for: rx, type: .withResponse)
|
||||
} else {
|
||||
peripheral.readValue(for: tx)
|
||||
}
|
||||
} catch { fail("Could not read comma’s pairing reply: \(error.localizedDescription)") }
|
||||
}
|
||||
}
|
||||
@@ -1,348 +0,0 @@
|
||||
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 system: [String: Any]?
|
||||
@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 { if !screenStatus.hasPrefix("Full comma display") { 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 telemetryTask: Task<Void, Never>?
|
||||
private var reconnectCount = 0
|
||||
private var retryDelay = 1.0
|
||||
private var streamHasFrame = false
|
||||
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 lastDiagnosticsHTTP: Int?
|
||||
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 BT 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)",
|
||||
"Live mode: \(live); phone visible: \(phoneVisible); phone active: \(phoneActive); CarPlay active: \(carPlayActive)",
|
||||
"Stream reconnect attempts: \(reconnectCount)",
|
||||
"Telemetry: \(status)", "Telemetry HTTP: \(lastDiagnosticsHTTP.map(String.init) ?? "No response yet")", "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 updateActivity() {
|
||||
let active = carPlayActive || (phoneVisible && phoneActive)
|
||||
if !active {
|
||||
task?.cancel(); task = nil; telemetryTask?.cancel(); telemetryTask = nil
|
||||
stopStream(); return
|
||||
}
|
||||
guard task == nil else { return }
|
||||
task = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
guard let self else { return }
|
||||
self.maintainStream()
|
||||
do { try await Task.sleep(nanoseconds: 500_000_000) } catch { return }
|
||||
}
|
||||
}
|
||||
telemetryTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
guard let self else { return }
|
||||
await self.pollDiagnostics()
|
||||
do { try await Task.sleep(nanoseconds: 2_000_000_000) } catch { return }
|
||||
}
|
||||
}
|
||||
}
|
||||
private func pollDiagnostics() async {
|
||||
guard Date().timeIntervalSince(lastDiagnostics) >= 3, let transport, transport.connected else { return }
|
||||
lastDiagnostics = Date()
|
||||
do {
|
||||
let response = try await transport.request(path: "/api/system/monitor", method: "GET", headers: [:], body: Data())
|
||||
try Task.checkCancellation()
|
||||
lastDiagnosticsHTTP = response.status
|
||||
let value = try JSONSerialization.jsonObject(with: response.bodyData) as? [String: Any] ?? [:]
|
||||
guard response.status == 200, value["schemaVersion"] as? Int == 1 else {
|
||||
throw BridgeError.message(value["error"] as? String ?? "System monitor unavailable.")
|
||||
}
|
||||
let cpu = (value["cpuPercent"] as? NSNumber)?.doubleValue
|
||||
let memory = value["memory"] as? [String: Any] ?? [:]
|
||||
let cores = value["cores"] as? [[String: Any]] ?? []
|
||||
system = value
|
||||
snapshot = DiagnosticSnapshot(ageSeconds: 0, engaged: nil, temperatures: [], rates:
|
||||
[DiagnosticMetric(name: "CPU load", value: cpu, unit: "%"),
|
||||
DiagnosticMetric(name: "Memory", value: (memory["percent"] as? NSNumber)?.doubleValue, unit: "%")] +
|
||||
cores.map { DiagnosticMetric(name: $0["name"] as? String ?? "CPU", value: ($0["percent"] as? NSNumber)?.doubleValue, unit: "%") }, capture: nil)
|
||||
receivedAt = Date(); status = "Connected · read only"
|
||||
} catch {
|
||||
if !Task.isCancelled { status = error.localizedDescription; system = nil; snapshot = nil; receivedAt = nil }
|
||||
}
|
||||
}
|
||||
private func maintainStream() {
|
||||
stopStream()
|
||||
screenStatus = "Open Cameras & Monitoring in Galaxy for SecretGood’s camera views. Cameras require local Wi-Fi."
|
||||
}
|
||||
private func stopStream(preserveFrame: Bool = false) {
|
||||
if !preserveFrame { 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(uiColor: .systemBackground))
|
||||
.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("Galaxy cameras", systemImage: "play.rectangle", description: Text(diagnostics.screenStatus))
|
||||
.frame(width: space.size.width, height: space.size.height)
|
||||
}
|
||||
}.background(Color(uiColor: .secondarySystemBackground), 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(Color(uiColor: .secondarySystemBackground), 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(Color(uiColor: .secondarySystemBackground), 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(Color(uiColor: .secondarySystemBackground), 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(Color(uiColor: .secondarySystemBackground), in: RoundedRectangle(cornerRadius: 16))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
struct ConnectionSettingsView: View {
|
||||
@ObservedObject var model: AppModel
|
||||
@ObservedObject var bluetooth: BluetoothTransport
|
||||
@ObservedObject var lan: LANTransport
|
||||
@ObservedObject var assets: GalaxyAssetStore
|
||||
@ObservedObject var server: LoopbackServer
|
||||
@ObservedObject var discovery: LANDiscovery
|
||||
@ObservedObject var location: PhoneLocation
|
||||
@ObservedObject var audio: AudioPairing
|
||||
let returningFromGalaxy: Bool
|
||||
let select: (CompanionTab) -> Void
|
||||
@Environment(\.openURL) private var openURL
|
||||
@State private var advanced = false
|
||||
@State private var confirmForget = false
|
||||
@State private var checked = false
|
||||
@State private var openAfterReconnect = false
|
||||
|
||||
private let accent = Color(red: 0.68, green: 0.48, blue: 0.96)
|
||||
private let background = Color(red: 0.035, green: 0.035, blue: 0.078)
|
||||
private let panel = Color(red: 0.09, green: 0.065, blue: 0.145)
|
||||
private let muted = Color(red: 0.70, green: 0.65, blue: 0.77)
|
||||
private var connected: Bool { model.transport.connected }
|
||||
private var pairing: Bool { model.pairingInProgress }
|
||||
private var needsPairing: Bool { model.mode != .lan && model.pairingKey.isEmpty }
|
||||
private var connecting: Bool { !connected && (bluetooth.connecting || bluetooth.isScanning) }
|
||||
private var primaryTitle: String {
|
||||
if pairing { return "Pairing…" }
|
||||
if connected { return model.opened ? "Open Galaxy" : "Preparing Galaxy…" }
|
||||
if connecting { return "Connecting…" }
|
||||
return needsPairing ? "Pair with comma" : "Reconnect"
|
||||
}
|
||||
private var checking: Bool { model.matchingGalaxy || assets.checking }
|
||||
private var status: String { pairing ? "Pairing with comma…" : connected ? "Connected via \(model.transport.label)" : connecting ? "Connecting to comma…" : "Not connected" }
|
||||
|
||||
init(model: AppModel, returningFromGalaxy: Bool, select: @escaping (CompanionTab) -> Void) {
|
||||
self.model = model; self.returningFromGalaxy = returningFromGalaxy; self.select = select
|
||||
bluetooth = model.bluetooth; lan = model.lan; assets = model.assets; server = model.server
|
||||
discovery = model.discovery; location = model.phoneLocation; audio = model.audioPairing
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(spacing: 8) {
|
||||
HStack {
|
||||
if returningFromGalaxy && model.opened {
|
||||
Button { select(.galaxy) } label: {
|
||||
Image(systemName: "chevron.left").frame(width: 44, height: 44)
|
||||
}.accessibilityLabel("Back to Galaxy")
|
||||
} else { Color.clear.frame(width: 44, height: 44) }
|
||||
Spacer(minLength: 0)
|
||||
Text(returningFromGalaxy ? "Settings" : "StarPilot BT")
|
||||
.font(.custom("Sora-Regular", size: 22).weight(.medium)).lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
Color.clear.frame(width: 44, height: 44)
|
||||
}
|
||||
ConnectionOrbit(route: connected ? model.transport.label : "", pairing: pairing)
|
||||
.padding(.bottom, 10)
|
||||
connectionPanel
|
||||
Text("PREFERENCES").font(.system(size: 11, weight: .medium)).tracking(1.2)
|
||||
.foregroundStyle(muted).frame(maxWidth: .infinity, alignment: .leading)
|
||||
preferences
|
||||
DisclosureGroup(isExpanded: $advanced) { advancedControls.padding(.top, 8) } label: {
|
||||
Text("Advanced connection options").font(.system(size: 13)).frame(minHeight: 30)
|
||||
}.padding(.horizontal, 14).padding(.vertical, 7).background(panel, in: RoundedRectangle(cornerRadius: 16))
|
||||
.overlay(RoundedRectangle(cornerRadius: 16).stroke(accent.opacity(0.16)))
|
||||
HStack(spacing: 18) {
|
||||
Button(model.loadingLegacyURL ? "Getting link…" : "Legacy Galaxy") {
|
||||
Task { if let url = await model.fetchLegacyURL() {
|
||||
openURL(url) { accepted in if !accepted { model.legacyMessage = "Couldn’t open your browser. Try again." } }
|
||||
} }
|
||||
}.disabled(model.loadingLegacyURL || pairing)
|
||||
Link("Support", destination: URL(string: "https://wiki.firestar.link/ticketsystem/")!)
|
||||
Link("Privacy", destination: URL(string: "https://github.com/natehuby76/ios-clone/blob/codex/secretgood-galaxy/docs/privacy.md")!)
|
||||
}.font(.system(size: 12)).frame(minHeight: 44)
|
||||
if !model.legacyMessage.isEmpty { message(model.legacyMessage) }
|
||||
if !server.error.isEmpty { message(server.error) }
|
||||
Text("StarPilot BT · \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")")
|
||||
.font(.system(size: 11)).foregroundStyle(muted)
|
||||
}.padding(.horizontal, 18).padding(.top, 0).padding(.bottom, 12)
|
||||
.frame(maxWidth: 460).frame(maxWidth: .infinity)
|
||||
}.scrollBounceBehavior(.basedOnSize).background(background).foregroundStyle(Color.white)
|
||||
.onChange(of: connected) { _, _ in openReconnectedGalaxy() }
|
||||
.onChange(of: model.opened) { _, _ in openReconnectedGalaxy() }
|
||||
.onChange(of: model.wantsConnection) { _, value in if !value { openAfterReconnect = false } }
|
||||
.tint(accent).preferredColorScheme(.dark)
|
||||
.confirmationDialog("Forget Bluetooth pairing?", isPresented: $confirmForget, titleVisibility: .visible) {
|
||||
Button("Forget pairing", role: .destructive) {
|
||||
model.disconnect(); bluetooth.forgetSavedDevice(); PairingKeyStore.remove(); model.pairingKey = ""
|
||||
lan.bind(to: nil); UserDefaults.standard.removeObject(forKey: "galaxy.comma.identity")
|
||||
}
|
||||
} message: { Text("This removes the saved app pairing. Pair your phone again to reconnect.") }
|
||||
}
|
||||
|
||||
private func openReconnectedGalaxy() {
|
||||
guard openAfterReconnect, connected, model.opened else { return }
|
||||
openAfterReconnect = false
|
||||
select(.galaxy)
|
||||
}
|
||||
|
||||
private var connectionPanel: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 10) {
|
||||
Image(model.transport.label == "Wi-Fi" ? "ConnectionWiFi" : "ConnectionBluetooth").renderingMode(.template).resizable().scaledToFit().frame(width: 20, height: 20).foregroundStyle(accent)
|
||||
.frame(width: 38, height: 38).background(accent.opacity(0.15), in: RoundedRectangle(cornerRadius: 12))
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("Your comma").font(.system(size: 17, weight: .medium))
|
||||
Text(status).font(.system(size: 11)).foregroundStyle(muted).accessibilityAddTraits(.updatesFrequently)
|
||||
}
|
||||
Spacer(minLength: 4)
|
||||
Text(pairing ? "Pairing…" : connected ? "Connected" : connecting ? "Connecting…" : "Offline")
|
||||
.font(.system(size: 10, weight: .medium)).foregroundStyle(pairing ? accent : connected ? .mint : muted)
|
||||
.padding(.horizontal, 9).padding(.vertical, 6)
|
||||
.background((pairing ? accent : connected ? Color.mint : muted).opacity(0.13), in: Capsule())
|
||||
}
|
||||
Picker("Connection mode", selection: $model.mode) {
|
||||
Text("Automatic").tag(ConnectionMode.automatic)
|
||||
Text("Bluetooth").tag(ConnectionMode.bluetooth)
|
||||
Text("Wi-Fi").tag(ConnectionMode.lan)
|
||||
}.pickerStyle(.segmented).disabled(pairing)
|
||||
Text(pairing ? "Keep Pair phone open on comma." : model.mode == .automatic ? "Wi-Fi first, Bluetooth as backup." : model.mode == .bluetooth ? "Local controls over Bluetooth." : "Uses your local Wi-Fi network.")
|
||||
.font(.system(size: 11)).foregroundStyle(muted)
|
||||
Button {
|
||||
if connected && model.opened { select(.galaxy) }
|
||||
else if needsPairing { model.pairWithComma() }
|
||||
else { openAfterReconnect = true; model.connect(); openReconnectedGalaxy() }
|
||||
} label: {
|
||||
HStack(spacing: 7) {
|
||||
if pairing { PairingSignal() }
|
||||
else if connecting || (connected && !model.opened) { ProgressView().controlSize(.small) }
|
||||
Text(primaryTitle)
|
||||
}.font(.system(size: 12, weight: .medium)).frame(maxWidth: .infinity, minHeight: 44)
|
||||
.background(LinearGradient(colors: [Color(red: 0.73, green: 0.55, blue: 1), accent], startPoint: .leading, endPoint: .trailing), in: Capsule())
|
||||
.foregroundStyle(Color(red: 0.12, green: 0.06, blue: 0.19))
|
||||
}.buttonStyle(.plain).disabled(pairing || connecting || (connected && !model.opened))
|
||||
if pairing {
|
||||
Button("Cancel pairing") { model.cancelPairing() }.font(.system(size: 12)).frame(maxWidth: .infinity, minHeight: 30)
|
||||
} else if model.connectionMessage != "Connected over \(model.transport.label)." && !connected {
|
||||
message(model.connectionMessage)
|
||||
}
|
||||
}.padding(14).background(LinearGradient(colors: [panel, background], startPoint: .topLeading, endPoint: .bottomTrailing), in: RoundedRectangle(cornerRadius: 22))
|
||||
.overlay(RoundedRectangle(cornerRadius: 22).stroke(accent.opacity(0.25)))
|
||||
}
|
||||
|
||||
private var preferences: some View {
|
||||
VStack(spacing: 0) {
|
||||
row("music.note", title: "Phone music", subtitle: audio.phase == .connected ? "Comma is the audio output" : pairing ? "Waiting for app pairing" : "Audio not verified") {
|
||||
Button("Set up") { model.startAudioPairing() }.disabled(!connected || pairing).font(.system(size: 12)).frame(minHeight: 44)
|
||||
}
|
||||
separator
|
||||
row("location", title: "Share phone location", subtitle: location.status.isEmpty ? "Optional" : location.status) {
|
||||
Toggle("Share phone location", isOn: Binding(get: { location.sharing }, set: { location.setSharing($0) })).labelsHidden()
|
||||
}
|
||||
separator
|
||||
row("rectangle.on.rectangle", title: "Galaxy screens", subtitle: pairing ? "Waiting for pairing" : checking ? "Checking version…" : checked && assets.readyRoot != nil ? "Up to date · just checked" : assets.readyRoot != nil ? "Saved from your comma" : "Not downloaded · needs Wi-Fi") {
|
||||
Button {
|
||||
Task { await model.checkGalaxyUpdates(); checked = true }
|
||||
} label: {
|
||||
if checking { ProgressView().controlSize(.small).accessibilityLabel("Checking Galaxy") }
|
||||
else { Text(checked ? assets.readyRoot != nil ? "✓ Checked" : "Retry" : "Check") }
|
||||
}.font(.system(size: 12)).frame(minHeight: 44).disabled(checking || !connected || !model.transport.usesLAN || pairing)
|
||||
}
|
||||
if checked && !checking { message(assets.status).padding(.horizontal, 14).padding(.bottom, 10) }
|
||||
separator
|
||||
row("chevron.left.forwardslash.chevron.right", title: "Developer mode", subtitle: "Diagnostics and logs") {
|
||||
Toggle("Developer mode", isOn: $model.developerMode).labelsHidden()
|
||||
}
|
||||
}.background(panel, in: RoundedRectangle(cornerRadius: 20))
|
||||
.overlay(RoundedRectangle(cornerRadius: 20).stroke(accent.opacity(0.23)))
|
||||
}
|
||||
|
||||
private var advancedControls: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
if model.developerMode {
|
||||
Toggle("Fast Bluetooth reads", isOn: $bluetooth.fastReads)
|
||||
message(bluetooth.fastReadFallback ? "Fast reads paused after an error. Reliable reads are active." : "Experimental. Turn off to use reliable reads.")
|
||||
Button("Open Dev / Logs") { select(.logs) }
|
||||
Divider()
|
||||
}
|
||||
if model.mode != .bluetooth {
|
||||
HStack {
|
||||
Button(discovery.searching ? "Stop discovery" : "Find comma on Wi-Fi") {
|
||||
if discovery.searching { discovery.stop() } else { discovery.start() }
|
||||
}.disabled(model.selectingDiscoveredComma || pairing)
|
||||
}
|
||||
message(discovery.status)
|
||||
ForEach(discovery.devices) { device in
|
||||
Button { Task { await model.selectDiscoveredComma(device) } } label: {
|
||||
VStack(alignment: .leading) { Text(device.name); Text(device.address).font(.caption) }
|
||||
}.disabled(model.selectingDiscoveredComma || pairing)
|
||||
}
|
||||
Toggle("Find address over Bluetooth", isOn: $model.findAddressAutomatically)
|
||||
TextField("Comma IP address", text: $model.address).keyboardType(.numbersAndPunctuation)
|
||||
.textInputAutocapitalization(.never).autocorrectionDisabled().textFieldStyle(.roundedBorder)
|
||||
message(lan.status)
|
||||
}
|
||||
if model.mode != .lan {
|
||||
Button("Pair again") { model.pairWithComma() }.disabled(pairing)
|
||||
SecureField("64-character pairing key", text: $model.pairingKey)
|
||||
.textInputAutocapitalization(.never).autocorrectionDisabled().textFieldStyle(.roundedBorder)
|
||||
Button(bluetooth.isScanning ? "Scanning…" : "Scan for comma") { model.wantsConnection = true; bluetooth.scan() }
|
||||
.disabled(bluetooth.isScanning || bluetooth.connecting || pairing)
|
||||
message(bluetooth.status)
|
||||
ForEach(bluetooth.devices) { device in
|
||||
Button(device.name) {
|
||||
model.opened = false; model.wantsConnection = true; lan.clearEndpoint(); 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)
|
||||
}.disabled(bluetooth.connecting || pairing)
|
||||
}
|
||||
if bluetooth.connecting { Button("Cancel Bluetooth connection") { bluetooth.disconnect() } }
|
||||
Button("Forget Bluetooth pairing", role: .destructive) { confirmForget = true }.disabled(pairing)
|
||||
}
|
||||
message(assets.status)
|
||||
if let url = model.legacyURL { Text(url.absoluteString).font(.caption).textSelection(.enabled) }
|
||||
Button("Disconnect") { model.disconnect() }.disabled(pairing)
|
||||
}.font(.system(size: 13)).buttonStyle(.bordered).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private var separator: some View { Rectangle().fill(accent.opacity(0.12)).frame(height: 1).padding(.leading, 42) }
|
||||
private func message(_ text: String) -> some View {
|
||||
Text(text).font(.system(size: 11)).foregroundStyle(muted).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
private func row<Control: View>(_ symbol: String, title: String, subtitle: String, @ViewBuilder control: () -> Control) -> some View {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: symbol).foregroundStyle(accent).frame(width: 20)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(title).font(.system(size: 13, weight: .medium))
|
||||
Text(subtitle).font(.system(size: 11)).foregroundStyle(muted).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
Spacer(minLength: 4)
|
||||
control().fixedSize(horizontal: true, vertical: false)
|
||||
}.padding(.horizontal, 13).padding(.vertical, 6).frame(minHeight: 56)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PairingSignal: View {
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
@State private var pulse = false
|
||||
var body: some View {
|
||||
HStack(alignment: .bottom, spacing: 2) {
|
||||
ForEach(0..<3) { index in
|
||||
Capsule().frame(width: 3, height: CGFloat(5 + index * 4))
|
||||
.opacity(reduceMotion || pulse ? 1 : 0.25)
|
||||
.animation(reduceMotion ? nil : .easeInOut(duration: 0.7).repeatForever(autoreverses: true).delay(Double(index) * 0.15), value: pulse)
|
||||
}
|
||||
}.frame(height: 15).onAppear { pulse = true }.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ConnectionOrbit: View {
|
||||
let route: String
|
||||
let pairing: Bool
|
||||
private let purple = Color(red: 0.68, green: 0.48, blue: 0.96)
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Ellipse().stroke(purple.opacity(0.5), lineWidth: 1).frame(width: 232, height: 64).rotationEffect(.degrees(12)).position(x: 132, y: 48)
|
||||
Ellipse().stroke(purple.opacity(0.35), style: StrokeStyle(lineWidth: 1, dash: [2, 4]))
|
||||
.frame(width: 258, height: 76).rotationEffect(.degrees(-9)).position(x: 132, y: 48)
|
||||
Circle().fill(LinearGradient(colors: [Color(red: 0.74, green: 0.53, blue: 1), purple], startPoint: .topLeading, endPoint: .bottomTrailing))
|
||||
.overlay(Circle().stroke(Color.white.opacity(0.6)))
|
||||
.overlay(Image("StarPilotMark").resizable().scaledToFit().padding(5))
|
||||
.shadow(color: purple.opacity(0.5), radius: 16).frame(width: 60, height: 60).position(x: 132, y: 43)
|
||||
node("ConnectionWiFi", angle: 155, active: route == "Wi-Fi")
|
||||
node("ConnectionBluetooth", angle: 110, active: route == "Bluetooth" || pairing)
|
||||
node("ConnectionNetwork", angle: -25, active: false)
|
||||
}.frame(width: 264, height: 88).accessibilityHidden(true)
|
||||
}
|
||||
private func node(_ symbol: String, angle: Double, active: Bool) -> some View {
|
||||
let theta = angle * .pi / 180, rotation = 12.0 * .pi / 180
|
||||
let x = 132 + 116 * cos(theta) * cos(rotation) - 32 * sin(theta) * sin(rotation)
|
||||
let y = 48 + 116 * cos(theta) * sin(rotation) + 32 * sin(theta) * cos(rotation)
|
||||
return Image(symbol).renderingMode(.template).resizable().scaledToFit().frame(width: 15, height: 15).foregroundStyle(active ? Color.white : Color.white.opacity(0.65))
|
||||
.frame(width: 30, height: 30).background(Color(red: 0.09, green: 0.075, blue: 0.15), in: Circle())
|
||||
.overlay(Circle().stroke(Color.white.opacity(active ? 0.75 : 0.4)))
|
||||
.shadow(color: purple.opacity(active ? 0.35 : 0), radius: 7).position(x: x, y: y)
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
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) }),
|
||||
["index.html", "manifest.webmanifest", "sentry-push-worker.js"].contains(file.path) || ["assets/", "css/", "js/", "vendor/", "data/"].contains(where: { file.path.hasPrefix($0) }),
|
||||
(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 == "index.html" }),
|
||||
files.contains(where: { $0.path == "js/boot.js" }),
|
||||
files.contains(where: { $0.path == "js/app.js" }),
|
||||
files.contains(where: { $0.path == "data/catalog.json" }),
|
||||
!files.contains(where: { $0.path == "data/runtime.json" || $0.path.hasSuffix(".sample.json") }) 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() }
|
||||
}
|
||||
|
||||
/// Comma's inventory of its Galaxy pages, from `GET /api/companion/web-manifest`.
|
||||
struct GalaxyListing: Decodable {
|
||||
let schema: Int
|
||||
let commit: String?
|
||||
let files: [GalaxyAssetManifest.File]
|
||||
}
|
||||
|
||||
/// One GET to comma over Wi-Fi/LAN: the HTTP status and body.
|
||||
typealias GalaxyPageFetch = @Sendable (_ path: String, _ limit: Int) async throws -> (status: Int, data: Data)
|
||||
|
||||
/// Keeps the Bluetooth copy of Galaxy matched to the pages comma serves, downloaded over Wi-Fi/LAN.
|
||||
@MainActor
|
||||
final class GalaxyAssetStore: ObservableObject {
|
||||
static let notDownloaded = "Galaxy screens aren’t downloaded yet. Connect to comma over Wi-Fi once."
|
||||
static let tooOld = "Comma’s software is too old to share Galaxy screens; update comma."
|
||||
@Published private(set) var status = GalaxyAssetStore.notDownloaded
|
||||
@Published private(set) var checking = false
|
||||
@Published private(set) var readyRoot: URL?
|
||||
var inUseRoot: URL?
|
||||
private let cacheRoot: URL
|
||||
private let defaults: UserDefaults
|
||||
init(cacheRoot: URL? = nil, defaults: UserDefaults = .standard) {
|
||||
self.cacheRoot = cacheRoot ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("DeviceGalaxyUpdates", isDirectory: true)
|
||||
self.defaults = defaults
|
||||
// Validate saved assets before trusting a previous completed update.
|
||||
if let hash = defaults.string(forKey: "galaxy.device.assets.manifest"), GalaxyAssetManifest.isHash(hash) {
|
||||
let root = self.cacheRoot.appendingPathComponent(hash, isDirectory: true)
|
||||
if Self.verify(root) { readyRoot = root; status = "Using Galaxy screens saved from comma." }
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
/// True when comma now runs a different build than the one the saved screens came from.
|
||||
func olderThan(commit: String?) -> Bool {
|
||||
guard readyRoot != nil, let saved = defaults.string(forKey: "galaxy.device.commit"), !saved.isEmpty,
|
||||
let commit, !commit.isEmpty else { return false }
|
||||
return saved != commit
|
||||
}
|
||||
/// Over Bluetooth nothing can be downloaded; tell the user when the saved screens are behind comma.
|
||||
func noteCommaBuild(commit: String?) {
|
||||
if olderThan(commit: commit) { status = "Galaxy screens are from an older comma build. Connect over Wi-Fi to refresh." }
|
||||
}
|
||||
/// Compares comma's inventory with the saved copy and downloads only what changed. Never skips on an unchanged commit.
|
||||
func check(fetch: @escaping GalaxyPageFetch, stillCurrent: () -> Bool = { true }) async {
|
||||
guard !checking else { return }
|
||||
checking = true
|
||||
status = "Checking comma for Galaxy updates…"
|
||||
defer { checking = false }
|
||||
var stage: URL?
|
||||
do {
|
||||
let (code, listingData) = try await fetch("/api/companion/web-manifest", 1_048_576)
|
||||
// Older comma builds answer 401 (no session) or 404 for the inventory path.
|
||||
if code == 401 || code == 404 { throw BridgeError.message(Self.tooOld) }
|
||||
guard code == 200 else { throw BridgeError.message("Comma returned HTTP \(code) for the Galaxy inventory.") }
|
||||
let listing = try JSONDecoder().decode(GalaxyListing.self, from: listingData)
|
||||
guard listing.schema == 1 else { throw BridgeError.message(Self.tooOld) }
|
||||
let manifest = GalaxyAssetManifest(schema: 1, nativeBridge: 1, files: listing.files.sorted { $0.path < $1.path })
|
||||
try manifest.validate()
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = .sortedKeys
|
||||
let data = try encoder.encode(manifest)
|
||||
let hash = GalaxyAssetManifest.digest(data)
|
||||
guard stillCurrent() else { throw CancellationError() }
|
||||
if readyRoot?.lastPathComponent == hash { defaults.set(listing.commit ?? "", forKey: "galaxy.device.commit"); status = "Galaxy matches comma."; 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)
|
||||
let saved = readyRoot
|
||||
var done = 0
|
||||
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)])
|
||||
try await withThrowingTaskGroup(of: (String, Data).self) { group in
|
||||
for file in batch {
|
||||
group.addTask {
|
||||
func matches(_ bytes: Data) -> Bool { bytes.count == file.size && GalaxyAssetManifest.digest(bytes) == file.sha256 }
|
||||
if let saved, let bytes = try? Data(contentsOf: saved.appendingPathComponent(file.path)), matches(bytes) { return (file.path, bytes) }
|
||||
let (code, bytes) = try await fetch("/" + file.path, max(file.size, 1))
|
||||
guard code == 200, matches(bytes) 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)
|
||||
}
|
||||
}
|
||||
done += batch.count
|
||||
status = "Preparing Galaxy update (\(done)/\(manifest.files.count))…"
|
||||
}
|
||||
guard stillCurrent() else { throw CancellationError() }
|
||||
try data.write(to: staging.appendingPathComponent("manifest.json"), options: .atomic)
|
||||
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.
|
||||
readyRoot = destination
|
||||
defaults.set(hash, forKey: "galaxy.device.assets.manifest")
|
||||
defaults.set(listing.commit ?? "", forKey: "galaxy.device.commit")
|
||||
if let contents = try? manager.contentsOfDirectory(at: cacheRoot, includingPropertiesForKeys: nil) {
|
||||
for root in contents where root.standardizedFileURL.path != destination.standardizedFileURL.path && root.standardizedFileURL.path != saved?.standardizedFileURL.path && root.standardizedFileURL.path != inUseRoot?.standardizedFileURL.path { try? manager.removeItem(at: root) }
|
||||
}
|
||||
status = "Galaxy screens updated from comma. Open Galaxy to use them."
|
||||
} catch {
|
||||
if let stage { try? FileManager.default.removeItem(at: stage) }
|
||||
let using = readyRoot == nil ? "No Galaxy screens are saved yet." : "Using your saved Galaxy screens."
|
||||
if let failure = error as? URLError {
|
||||
status = "Couldn’t reach comma to check Galaxy updates (network error \(failure.code.rawValue)). \(using)"
|
||||
} else if let failure = error as? BridgeError {
|
||||
status = "\(failure.localizedDescription) \(using)"
|
||||
} else if error is CancellationError {
|
||||
status = "Galaxy update cancelled. \(using)"
|
||||
} else {
|
||||
status = "Galaxy update could not be read or saved. \(using)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,722 +0,0 @@
|
||||
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", logs = "Dev / Logs", connections = "Settings"
|
||||
var id: String { rawValue }
|
||||
var isDeveloperPage: Bool { self == .live || self == .diagnostics || self == .logs }
|
||||
var icon: String {
|
||||
switch self {
|
||||
case .galaxy: "sparkles"
|
||||
case .live: "play.rectangle"
|
||||
case .diagnostics: "chart.xyaxis.line"
|
||||
case .logs: "ladybug"
|
||||
case .connections: "gearshape.fill"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LegacyGalaxyStatus: Decodable {
|
||||
let paired: Bool
|
||||
let url: String
|
||||
var browserURL: URL? {
|
||||
guard let parsed = URL(string: url), parsed.scheme == "https",
|
||||
parsed.host == "galaxy.firestar.link", parsed.port == nil,
|
||||
parsed.user == nil, parsed.password == nil, parsed.query == nil, parsed.fragment == nil,
|
||||
parsed.path.range(of: "^/[A-Za-z0-9]{16}$", options: .regularExpression) != nil else { return nil }
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class AppModel: ObservableObject {
|
||||
static let shared = AppModel()
|
||||
let diagnostics = CompanionDiagnostics()
|
||||
let galaxyPage = GalaxyPageDiagnostics()
|
||||
let connectionLog = ConnectionEventLog()
|
||||
let discovery = LANDiscovery()
|
||||
@Published var selectingDiscoveredComma = false
|
||||
private var lastRoute = "Reconnecting…"
|
||||
@Published var showDiagnostics = false
|
||||
@Published var showAudioPairing = false
|
||||
private var offerAudioPairing = false
|
||||
private var audioWindowOpen = false
|
||||
private let claimer = ClaimTransport()
|
||||
lazy var audioPairing = AudioPairing(transport: { [weak self] in self?.transport })
|
||||
lazy var phoneLocation: PhoneLocation = {
|
||||
let value = PhoneLocation(transport: { [weak self] in self?.transport })
|
||||
value.onSharingChanged = { [weak self] _ in self?.updateMonitoring() }
|
||||
return value
|
||||
}()
|
||||
@Published var tab: CompanionTab = .connections
|
||||
@Published var developerMode = UserDefaults.standard.bool(forKey: "galaxy.app.developerMode") {
|
||||
didSet {
|
||||
UserDefaults.standard.set(developerMode, forKey: "galaxy.app.developerMode")
|
||||
if !developerMode {
|
||||
if tab.isDeveloperPage { tab = opened ? .galaxy : .connections }
|
||||
diagnostics.live = false
|
||||
diagnostics.phoneVisible = false
|
||||
showDiagnostics = false
|
||||
}
|
||||
}
|
||||
}
|
||||
private var galaxyRecoveryTask: Task<Void, Never>?
|
||||
private var lastAutomaticGalaxyRecovery: TimeInterval = -.infinity
|
||||
func recoverGalaxy(automatic: Bool = true, reload: Bool = true) {
|
||||
guard phoneActive, galaxyRecoveryTask == nil else { return }
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
if automatic && reload {
|
||||
guard now - lastAutomaticGalaxyRecovery >= 30 else {
|
||||
galaxyPage.record("Automatic page recovery paused; use Retry Galaxy")
|
||||
return
|
||||
}
|
||||
lastAutomaticGalaxyRecovery = now
|
||||
}
|
||||
galaxyRecoveryTask = Task { @MainActor in
|
||||
defer { self.galaxyRecoveryTask = nil }
|
||||
let previousURL = self.server.url
|
||||
let healthy = await self.server.ensureAvailable()
|
||||
guard self.phoneActive else { return }
|
||||
if healthy {
|
||||
if self.opened && (reload || self.galaxyPage.stalled || previousURL != self.server.url) {
|
||||
self.galaxyPage.record("Local server checked; recreating Galaxy web page")
|
||||
self.galaxyPage.retry()
|
||||
}
|
||||
} else { self.galaxyPage.fail("Local server unavailable after recovery attempt") }
|
||||
}
|
||||
}
|
||||
private var phoneActive = false
|
||||
private var carPlayActive = false
|
||||
private var monitorTask: Task<Void, Never>?
|
||||
func setPhoneActive(_ active: Bool) { phoneActive = active; if !active { automaticLAN?.cancel() }; diagnostics.phoneActive = active; if !active { discovery.stop() }; updateMonitoring() }
|
||||
func setCarPlayActive(_ active: Bool) { carPlayActive = active; diagnostics.carPlayActive = active; updateMonitoring() }
|
||||
private func updateMonitoring() {
|
||||
// Sharing phone GPS keeps the app running in the background, so keep reconnecting too.
|
||||
if phoneActive || carPlayActive || phoneLocation.sharing {
|
||||
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 {
|
||||
automaticLAN?.cancel(); lanProbeTask?.cancel()
|
||||
transport.mode = mode
|
||||
UserDefaults.standard.set(mode.rawValue, forKey: "galaxy.connection.mode")
|
||||
if mode == .lan { bluetooth.disconnect() }
|
||||
if mode == .bluetooth { discovery.stop(); lan.invalidate(reason: "Bluetooth-only mode selected") }
|
||||
logConnection("Connection mode selected: \(mode.title)")
|
||||
}
|
||||
}
|
||||
@Published var showConnections = false
|
||||
@Published var pairingInProgress = false
|
||||
@Published var opened = false
|
||||
@Published var connectionMessage = "Choose a connection, or use Automatic for Wi-Fi with Bluetooth fallback."
|
||||
@Published var wantsConnection = true
|
||||
@Published var loadingLegacyURL = false
|
||||
@Published var legacyMessage = ""
|
||||
@Published var legacyURL: URL?
|
||||
let bluetooth: BluetoothTransport
|
||||
let lan: LANTransport
|
||||
let transport: PreferredTransport
|
||||
let assets: GalaxyAssetStore
|
||||
let server: LoopbackServer
|
||||
private let pathMonitor = NWPathMonitor()
|
||||
private var lastNetworkPath = ""
|
||||
private var lastReconnect = Date.distantPast
|
||||
private var lastAddressCheck = Date.distantPast
|
||||
private var identitySession = ""
|
||||
private var addressCheckSession = ""
|
||||
private var localAddressNetwork = ""
|
||||
private var automaticLAN: Task<Void, Never>?
|
||||
private var lanProbeTask: Task<Void, Never>?
|
||||
private var lastLANDiscovery = Date.distantPast
|
||||
private var triedLANAddresses = Set<String>()
|
||||
/// One step for the app and music: comma's open pairing window gives this iPhone its key, then music is set up in the same window.
|
||||
func pairWithComma() {
|
||||
guard !pairingInProgress else { return }
|
||||
pairingInProgress = true
|
||||
offerAudioPairing = false
|
||||
showAudioPairing = false
|
||||
bluetooth.disconnect(reason: "Starting new phone pairing")
|
||||
connectionMessage = "Open Settings → Bluetooth → Pair phone on comma (or Pair phone in Galaxy). Looking for comma…"
|
||||
Task { @MainActor in
|
||||
defer { pairingInProgress = false }
|
||||
if await LANPairing.openWindow(over: lan) {
|
||||
connectionMessage = "Opened comma’s pairing window over Wi-Fi. Looking for comma…"
|
||||
}
|
||||
do { importClaim(try await claimer.claim(name: UIDevice.current.name)) }
|
||||
catch is CancellationError { connectionMessage = "Pairing cancelled." }
|
||||
catch { connectionMessage = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
func cancelPairing() { claimer.cancel() }
|
||||
private func importClaim(_ outcome: ClaimTransport.Outcome) {
|
||||
// The key is saved only after the encrypted handshake, like any imported key.
|
||||
opened = false
|
||||
wantsConnection = true
|
||||
bluetooth.forgetSavedDevice()
|
||||
PairingKeyStore.stage(PairingCode(key: outcome.result.key, id: outcome.result.id))
|
||||
lan.clearEndpoint()
|
||||
lan.bind(to: nil)
|
||||
address = ""
|
||||
identitySession = ""
|
||||
addressCheckSession = ""
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.comma.identity")
|
||||
UserDefaults.standard.removeObject(forKey: "galaxy.lan.address")
|
||||
UserDefaults.standard.set(outcome.deviceID.uuidString, forKey: "galaxy.bluetooth.device")
|
||||
pairingKey = outcome.result.key
|
||||
if mode == .lan { mode = .automatic }
|
||||
connectionMessage = "Paired. Connecting to comma…"
|
||||
offerAudioPairing = true
|
||||
audioWindowOpen = true
|
||||
lastReconnect = Date()
|
||||
bluetooth.reconnectSaved(pairingKey: pairingKey)
|
||||
if !bluetooth.connecting { bluetooth.scan() }
|
||||
}
|
||||
init() {
|
||||
let bluetooth = BluetoothTransport()
|
||||
let lan = LANTransport()
|
||||
let transport = PreferredTransport(lan: lan, bluetooth: bluetooth, invalidateLAN: { lan.invalidate(reason: $0) })
|
||||
let assets = GalaxyAssetStore()
|
||||
self.bluetooth = bluetooth; self.lan = lan; self.transport = transport; self.assets = assets
|
||||
lan.bind(to: UserDefaults.standard.string(forKey: "galaxy.comma.identity"))
|
||||
let cache = GalaxyReadCache(transport: transport, sessionID: {
|
||||
transport.usesLAN ? "lan-" + lan.generation : "ble-" + bluetooth.sessionIdentifier
|
||||
})
|
||||
server = LoopbackServer(transport: cache, webRoot: assets.readyRoot)
|
||||
transport.mode = mode
|
||||
diagnostics.transport = transport; diagnostics.lan = lan
|
||||
galaxyPage.recover = { [weak self] automatic in self?.recoverGalaxy(automatic: automatic) }
|
||||
server.start()
|
||||
discovery.onEvent = { [weak self] reason in self?.connectionLog.record(reason) }
|
||||
discovery.onDevicesChanged = { [weak self] in self?.discoverAutomaticLAN() }
|
||||
lan.onEvent = { [weak self] reason in self?.logConnection(reason) }
|
||||
bluetooth.onEvent = { [weak self] reason in self?.logConnection(reason) }
|
||||
claimer.onEvent = { [weak self] reason in self?.connectionLog.record(reason) }
|
||||
pathMonitor.pathUpdateHandler = { [weak self] path in
|
||||
Task { @MainActor in
|
||||
guard let self else { return }
|
||||
let route = path.usesInterfaceType(.wifi) ? "Wi-Fi" : path.usesInterfaceType(.cellular) ? "cellular" : "other"
|
||||
let reason = "iOS network path updated: \(path.status == .satisfied ? "available" : "unavailable"), \(route), expensive=\(path.isExpensive), constrained=\(path.isConstrained)"
|
||||
let interfaces = path.availableInterfaces
|
||||
.filter { path.usesInterfaceType($0.type) }
|
||||
.map { "\($0.name):\($0.index)" }.sorted().joined(separator: ",")
|
||||
let fingerprint = "\(path.status)|\(route)|\(interfaces)|ipv4=\(path.supportsIPv4)|\(LANDiscovery.networkSignature())"
|
||||
guard fingerprint != self.lastNetworkPath else { return }
|
||||
self.lastNetworkPath = fingerprint
|
||||
self.connectionLog.record(reason)
|
||||
self.automaticLAN?.cancel(); self.lanProbeTask?.cancel()
|
||||
self.discovery.networkChanged()
|
||||
self.triedLANAddresses.removeAll()
|
||||
self.lastLANDiscovery = .distantPast
|
||||
self.lan.invalidate(reason: reason)
|
||||
self.lastAddressCheck = .distantPast
|
||||
self.discoverAutomaticLAN()
|
||||
}
|
||||
}
|
||||
pathMonitor.start(queue: .main)
|
||||
updateMonitoring()
|
||||
}
|
||||
deinit { pathMonitor.cancel() }
|
||||
private func logConnection(_ reason: String) {
|
||||
let route = transport.label
|
||||
if route != lastRoute {
|
||||
connectionLog.record("\(lastRoute) → \(route): \(reason)")
|
||||
lastRoute = route
|
||||
} else { connectionLog.record("\(route): \(reason)") }
|
||||
}
|
||||
func connect() {
|
||||
legacyURL = nil
|
||||
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
|
||||
localAddressNetwork = ""
|
||||
connectionMessage = "Checking your comma…"
|
||||
} catch { connectionMessage = error.localizedDescription }
|
||||
}
|
||||
func startAudioPairing() {
|
||||
guard transport.connected else { return }
|
||||
showAudioPairing = true
|
||||
let windowOpen = audioWindowOpen
|
||||
audioWindowOpen = false
|
||||
audioPairing.start(windowOpen: windowOpen)
|
||||
}
|
||||
private var openingGalaxy = false
|
||||
@Published private(set) var matchingGalaxy = false
|
||||
private var lastGalaxyMatch = Date.distantPast
|
||||
|
||||
func applyMatchedGalaxy() {
|
||||
guard opened, let root = assets.readyRoot, root != assets.inUseRoot else { return }
|
||||
assets.inUseRoot = root
|
||||
server.useWebRoot(root)
|
||||
recoverGalaxy(automatic: false)
|
||||
}
|
||||
|
||||
func checkGalaxyUpdates() async {
|
||||
guard wantsConnection, transport.connected, !matchingGalaxy else { return }
|
||||
matchingGalaxy = true
|
||||
lastGalaxyMatch = Date()
|
||||
defer { matchingGalaxy = false }
|
||||
let bleSession = bluetooth.sessionIdentifier
|
||||
let lanSession = lan.generation
|
||||
let stillCurrent = { self.wantsConnection && self.transport.connected && self.bluetooth.sessionIdentifier == bleSession && self.lan.generation == lanSession }
|
||||
if transport.usesLAN {
|
||||
// Pages come straight from comma, never through the Bluetooth bridge or the read cache.
|
||||
let lan = self.lan
|
||||
await assets.check(fetch: { path, _ in
|
||||
let response = path.hasPrefix("/api/") ? try await lan.request(path: path, method: "GET", headers: [:], body: Data()) : try await lan.page(path: path)
|
||||
return (response.status, response.bodyData)
|
||||
}, stillCurrent: stillCurrent)
|
||||
} else if assets.readyRoot != nil {
|
||||
// Over Bluetooth nothing can be downloaded; just say when the saved screens are behind comma.
|
||||
guard let response = try? await transport.request(path: "/api/software/status?history=0", method: "GET", headers: [:], body: Data()),
|
||||
response.status == 200, stillCurrent(),
|
||||
let status = try? JSONSerialization.jsonObject(with: response.bodyData) as? [String: Any],
|
||||
let installed = status["installed"] as? [String: Any] else { return }
|
||||
assets.noteCommaBuild(commit: installed["commit"] as? String)
|
||||
}
|
||||
}
|
||||
func openIfReady() {
|
||||
guard wantsConnection, transport.connected, !opened, !openingGalaxy else { return }
|
||||
openingGalaxy = true
|
||||
Task { @MainActor in
|
||||
defer { openingGalaxy = false }
|
||||
if transport.usesLAN ? Date().timeIntervalSince(lastGalaxyMatch) > 15 : assets.readyRoot != nil && !matchingGalaxy {
|
||||
await checkGalaxyUpdates()
|
||||
}
|
||||
guard wantsConnection, transport.connected, !opened else { return }
|
||||
// Bluetooth Galaxy runs from screens saved from comma; the first download needs Wi-Fi/LAN.
|
||||
// Over Wi-Fi/LAN an older comma that cannot share its screens still opens, read live.
|
||||
guard let root = assets.readyRoot else {
|
||||
guard transport.usesLAN else { return }
|
||||
assets.inUseRoot = nil
|
||||
opened = true
|
||||
return
|
||||
}
|
||||
assets.inUseRoot = root
|
||||
server.useWebRoot(root)
|
||||
opened = true
|
||||
}
|
||||
}
|
||||
func disconnect() {
|
||||
legacyURL = nil
|
||||
automaticLAN?.cancel(); lanProbeTask?.cancel()
|
||||
discovery.stop()
|
||||
wantsConnection = false; opened = false
|
||||
bluetooth.disconnect(reason: "User selected Disconnect"); lan.invalidate(reason: "User selected Disconnect")
|
||||
connectionMessage = "Disconnected."
|
||||
}
|
||||
func selectDiscoveredComma(_ device: DiscoveredComma) async {
|
||||
guard !selectingDiscoveredComma, mode != .bluetooth else { return }
|
||||
discovery.stop()
|
||||
selectingDiscoveredComma = true
|
||||
defer { selectingDiscoveredComma = false }
|
||||
// Advertised names and addresses are discovery hints, not pairing credentials.
|
||||
let candidate = LANTransport()
|
||||
candidate.bind(to: lan.expectedDeviceID)
|
||||
let originalGeneration = lan.generation
|
||||
let originalMode = mode
|
||||
do {
|
||||
try candidate.configure(address: device.address)
|
||||
guard await candidate.probe() else {
|
||||
connectionMessage = "Found a device, but Galaxy is unavailable or it doesn’t match your paired comma."
|
||||
connectionLog.record("Discovered comma rejected by LAN verification")
|
||||
return
|
||||
}
|
||||
guard lan.generation == originalGeneration, mode == originalMode, phoneActive else {
|
||||
connectionMessage = "Connection changed. Select the comma again."
|
||||
return
|
||||
}
|
||||
lan.bind(to: candidate.verifiedDeviceID)
|
||||
UserDefaults.standard.set(candidate.verifiedDeviceID, forKey: "galaxy.comma.identity")
|
||||
address = device.address
|
||||
connect()
|
||||
connectionLog.record("User selected a discovered comma; LAN verification passed")
|
||||
} catch {
|
||||
connectionMessage = "Couldn’t connect to the discovered comma. Try again or enter its IP."
|
||||
}
|
||||
}
|
||||
func fetchLegacyURL() async -> URL? {
|
||||
guard !loadingLegacyURL else { return nil }
|
||||
legacyMessage = ""
|
||||
legacyURL = nil
|
||||
guard wantsConnection, transport.connected else {
|
||||
legacyMessage = "Connect to your comma first to get its Galaxy link."
|
||||
return nil
|
||||
}
|
||||
loadingLegacyURL = true
|
||||
defer { loadingLegacyURL = false }
|
||||
let lanSession = lan.generation
|
||||
let bluetoothSession = bluetooth.sessionIdentifier
|
||||
do {
|
||||
let response = try await transport.request(path: "/api/galaxy/status", method: "GET", headers: [:], body: Data())
|
||||
guard wantsConnection, transport.connected, lan.generation == lanSession,
|
||||
bluetooth.sessionIdentifier == bluetoothSession else {
|
||||
throw BridgeError.message("Connection changed. Try opening legacy Galaxy again.")
|
||||
}
|
||||
guard response.status == 200 else {
|
||||
throw BridgeError.message("Couldn’t get your comma’s Galaxy link (HTTP \(response.status)).")
|
||||
}
|
||||
let status = try JSONDecoder().decode(LegacyGalaxyStatus.self, from: response.bodyData)
|
||||
guard status.paired else {
|
||||
throw BridgeError.message("Set up legacy Galaxy pairing on your comma first. Bluetooth pairing is separate.")
|
||||
}
|
||||
guard let url = status.browserURL else {
|
||||
throw BridgeError.message("Your comma hasn’t provided a valid Galaxy link. Check its legacy Galaxy pairing.")
|
||||
}
|
||||
legacyURL = url
|
||||
connectionLog.record("Comma-specific legacy Galaxy link validated")
|
||||
return url
|
||||
} catch {
|
||||
connectionLog.record("Comma-specific legacy Galaxy link unavailable")
|
||||
legacyMessage = (error as? BridgeError)?.localizedDescription ?? "Couldn’t get your comma’s Galaxy link. Check the connection and try again."
|
||||
return nil
|
||||
}
|
||||
}
|
||||
private func learnAddress() async {
|
||||
guard bluetooth.connected, Date().timeIntervalSince(lastAddressCheck) >= 20 || addressCheckSession != bluetooth.sessionIdentifier else { return }
|
||||
lastAddressCheck = Date()
|
||||
let session = bluetooth.sessionIdentifier
|
||||
let networkPath = lastNetworkPath
|
||||
addressCheckSession = session
|
||||
do {
|
||||
if identitySession != session {
|
||||
let identity = try await bluetooth.request(path: "/data/runtime.json", method: "GET", headers: [:], body: Data())
|
||||
guard !Task.isCancelled, 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
|
||||
}
|
||||
let network = session + "|" + networkPath
|
||||
guard findAddressAutomatically, !lan.connected, localAddressNetwork != network else { return }
|
||||
let generation = lan.generation
|
||||
let response = try await bluetooth.request(path: "/api/local-access", method: "GET", headers: [:], body: Data())
|
||||
guard !Task.isCancelled, wantsConnection, mode != .bluetooth, bluetooth.sessionIdentifier == session, response.status == 200,
|
||||
lastNetworkPath == networkPath, lan.generation == generation, !lan.connected,
|
||||
!response.bodyData.isEmpty else { return }
|
||||
if let ip = LANTransport.reportedAddress(response.bodyData) {
|
||||
localAddressNetwork = network
|
||||
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. */ }
|
||||
}
|
||||
private func discoverAutomaticLAN() {
|
||||
guard phoneActive, wantsConnection, mode == .automatic,
|
||||
!pairingInProgress, !selectingDiscoveredComma, !lan.connected,
|
||||
let identity = lan.expectedDeviceID else { return }
|
||||
if !discovery.searching, Date().timeIntervalSince(lastLANDiscovery) >= 20 {
|
||||
lastLANDiscovery = Date()
|
||||
triedLANAddresses.removeAll()
|
||||
discovery.start()
|
||||
}
|
||||
guard automaticLAN == nil else { return }
|
||||
let addresses = discovery.devices.map(\.address).filter { !triedLANAddresses.contains($0) }
|
||||
guard !addresses.isEmpty else { return }
|
||||
triedLANAddresses.formUnion(addresses)
|
||||
let generation = lan.generation
|
||||
automaticLAN = Task { @MainActor in
|
||||
defer { self.automaticLAN = nil }
|
||||
let stillCurrent = {
|
||||
self.phoneActive && self.wantsConnection && self.mode == .automatic
|
||||
&& !self.pairingInProgress && !self.selectingDiscoveredComma && !self.lan.connected
|
||||
&& self.lan.generation == generation && self.lan.expectedDeviceID == identity
|
||||
}
|
||||
let address = await LANDiscoveryMatch.first(addresses: addresses, expectedDeviceID: identity, stillCurrent: stillCurrent) { address, identity in
|
||||
let candidate = LANTransport()
|
||||
candidate.bind(to: identity)
|
||||
guard (try? candidate.configure(address: address)) != nil else { return false }
|
||||
return await candidate.probe()
|
||||
}
|
||||
guard let address, !Task.isCancelled, stillCurrent() else { return }
|
||||
do { try self.lan.configure(address: address) } catch { return }
|
||||
self.address = address
|
||||
UserDefaults.standard.set(address, forKey: "galaxy.lan.address")
|
||||
if await self.lan.probe() {
|
||||
self.discovery.stop()
|
||||
self.connectionLog.record("Automatic Wi-Fi discovery verified the paired comma")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func probeLocalConnection() {
|
||||
guard lanProbeTask == nil else { return }
|
||||
lanProbeTask = Task { @MainActor in
|
||||
defer { self.lanProbeTask = nil }
|
||||
await self.learnAddress()
|
||||
guard !Task.isCancelled, self.wantsConnection, self.mode != .bluetooth else { return }
|
||||
if self.lan.endpoint == nil, !self.address.isEmpty {
|
||||
do { try self.lan.configure(address: self.address) }
|
||||
catch { self.connectionMessage = error.localizedDescription }
|
||||
}
|
||||
_ = await self.lan.probe()
|
||||
if !Task.isCancelled, self.lan.connected { self.discovery.stop() }
|
||||
}
|
||||
}
|
||||
|
||||
func monitor() async {
|
||||
while !Task.isCancelled {
|
||||
if wantsConnection && !pairingInProgress {
|
||||
if mode != .lan, !bluetooth.connected, !bluetooth.connecting, !bluetooth.isScanning,
|
||||
!pairingKey.isEmpty, Date().timeIntervalSince(lastReconnect) >= 25 {
|
||||
lastReconnect = Date()
|
||||
bluetooth.reconnectSaved(pairingKey: pairingKey)
|
||||
}
|
||||
if mode != .bluetooth {
|
||||
discoverAutomaticLAN()
|
||||
probeLocalConnection()
|
||||
}
|
||||
guard !pairingInProgress else { continue }
|
||||
if transport.label != lastRoute { logConnection("Connection availability changed") }
|
||||
if transport.connected {
|
||||
openIfReady()
|
||||
if Date().timeIntervalSince(lastGalaxyMatch) > 60 && !openingGalaxy {
|
||||
Task { await self.checkGalaxyUpdates() }
|
||||
}
|
||||
connectionMessage = "Connected over \(transport.label)." + (opened || assets.readyRoot != nil ? "" : " " + assets.status)
|
||||
if offerAudioPairing { offerAudioPairing = false; startAudioPairing() }
|
||||
} else if mode == .bluetooth {
|
||||
connectionMessage = "Reconnecting over Bluetooth. If you forgot this phone on comma, open Pair phone on comma and Pair with comma here."
|
||||
} 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
|
||||
@ObservedObject var discovery: LANDiscovery
|
||||
@ObservedObject var galaxyPage: GalaxyPageDiagnostics
|
||||
@State private var hasVisitedGalaxy = false
|
||||
private var galaxyColorScheme: ColorScheme? {
|
||||
guard model.tab == .galaxy, let dark = galaxyPage.darkAppearance else { return nil }
|
||||
return dark ? .dark : .light
|
||||
}
|
||||
private var editorFocused: Bool { model.tab == .galaxy && galaxyPage.landscapeEditor }
|
||||
@Environment(\.openURL) private var openURL
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
init(model: AppModel) {
|
||||
self.model = model; bluetooth = model.bluetooth; lan = model.lan; assets = model.assets; server = model.server; discovery = model.discovery; galaxyPage = model.galaxyPage
|
||||
}
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
if !editorFocused && model.tab != .connections {
|
||||
VStack(spacing: 14) {
|
||||
HStack {
|
||||
if !model.developerMode && model.tab == .connections {
|
||||
if model.opened {
|
||||
Button { select(.galaxy) } label: {
|
||||
Image(systemName: "chevron.left").font(.body.weight(.semibold))
|
||||
.frame(width: 36, height: 36)
|
||||
}.buttonStyle(.plain).accessibilityLabel("Back to Galaxy")
|
||||
}
|
||||
Text("Settings").font(.title3.bold())
|
||||
} else {
|
||||
Text("StarPilot BT").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(Color(uiColor: .secondarySystemBackground), in: Capsule())
|
||||
if !model.developerMode && model.tab != .connections {
|
||||
Button { select(.connections) } label: {
|
||||
Image(systemName: "gearshape.fill").font(.body.weight(.semibold))
|
||||
.frame(width: 36, height: 36)
|
||||
.background(Color(uiColor: .secondarySystemBackground), in: Circle())
|
||||
}.buttonStyle(.plain).accessibilityLabel("Settings")
|
||||
}
|
||||
}
|
||||
if model.developerMode {
|
||||
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 : 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 : Color(uiColor: .tertiarySystemBackground), in: Circle())
|
||||
.foregroundStyle(model.tab == .connections ? Color.white : Color.secondary)
|
||||
Text("Settings").font(.system(size: 10, weight: .semibold))
|
||||
}.frame(width: 60).padding(.vertical, 4)
|
||||
.foregroundStyle(model.tab == .connections ? Color.primary : Color.secondary)
|
||||
}.buttonStyle(.plain).accessibilityAddTraits(model.tab == .connections ? .isSelected : [])
|
||||
}.padding(4).background(Color(uiColor: .secondarySystemBackground), 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, diagnostics: model.galaxyPage,
|
||||
isActive: model.tab == .galaxy && scenePhase == .active) {
|
||||
model.galaxyPage.report(server: server, connection: model.transport.label)
|
||||
}
|
||||
.opacity(model.tab == .galaxy ? 1 : 0)
|
||||
.allowsHitTesting(model.tab == .galaxy)
|
||||
.accessibilityHidden(model.tab != .galaxy)
|
||||
} else if model.opened && model.tab == .galaxy {
|
||||
VStack(spacing: 16) {
|
||||
if server.error.isEmpty { ProgressView("Reconnecting Galaxy…") }
|
||||
else { Text(server.error).multilineTextAlignment(.center) }
|
||||
Button("Retry Galaxy") { model.recoverGalaxy(automatic: false) }.buttonStyle(.bordered)
|
||||
}.padding(24)
|
||||
}
|
||||
if model.developerMode && model.tab == .logs {
|
||||
DeveloperLogsView(model: model, log: model.connectionLog)
|
||||
} else if model.developerMode && (model.tab == .live || model.tab == .diagnostics) {
|
||||
CompanionView(diagnostics: model.diagnostics)
|
||||
} else if model.tab == .connections || !model.opened {
|
||||
ConnectionSettingsView(model: model, returningFromGalaxy: hasVisitedGalaxy, select: select)
|
||||
}
|
||||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
.background(model.tab == .galaxy && galaxyPage.darkAppearance == true
|
||||
? Color(red: 0.06, green: 0.05, blue: 0.09) : Color(uiColor: .systemBackground))
|
||||
.preferredColorScheme(galaxyColorScheme)
|
||||
.ignoresSafeArea(.container, edges: editorFocused ? .all : [])
|
||||
.statusBarHidden(editorFocused)
|
||||
.onChange(of: model.showConnections) { _, show in
|
||||
if show { select(.connections); model.showConnections = false }
|
||||
}
|
||||
.onChange(of: model.showDiagnostics) { _, show in
|
||||
if show { if model.developerMode { select(.live) }; model.showDiagnostics = false }
|
||||
}
|
||||
.onChange(of: bluetooth.connected) { _, connected in if connected { model.openIfReady() } }
|
||||
.sheet(isPresented: $model.showAudioPairing, onDismiss: { model.audioPairing.dismiss() }) {
|
||||
AudioPairingSheet(pairing: model.audioPairing) { model.showAudioPairing = false }
|
||||
}
|
||||
.task(id: scenePhase) {
|
||||
model.setPhoneActive(scenePhase == .active)
|
||||
if scenePhase == .active { model.recoverGalaxy(reload: false); await model.checkGalaxyUpdates() }
|
||||
}
|
||||
}
|
||||
private func select(_ requestedTab: CompanionTab) {
|
||||
let tab = requestedTab.isDeveloperPage && !model.developerMode ? (model.opened ? CompanionTab.galaxy : .connections) : requestedTab
|
||||
if tab != .connections { discovery.stop() }
|
||||
model.tab = tab
|
||||
if tab == .galaxy { hasVisitedGalaxy = true; model.applyMatchedGalaxy() }
|
||||
model.diagnostics.live = tab == .live
|
||||
}
|
||||
private let brandPurple = Color(red: 139.0 / 255, green: 92.0 / 255, blue: 246.0 / 255)
|
||||
|
||||
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class ConnectionEventLog: ObservableObject {
|
||||
@Published private(set) var events: [String] = []
|
||||
@Published var section = "Connections"
|
||||
@Published var detail = ""
|
||||
@Published var copied = false
|
||||
private var lastEvent = ""
|
||||
func record(_ event: String) {
|
||||
guard event != lastEvent else { return }
|
||||
lastEvent = event
|
||||
events.append("\(ISO8601DateFormatter().string(from: Date())) \(event.prefix(300))")
|
||||
if events.count > 100 { events.removeFirst(events.count - 100) }
|
||||
}
|
||||
func clear() { events.removeAll(); lastEvent = ""; detail = ""; copied = false }
|
||||
func report(model: AppModel) -> String {
|
||||
let info = Bundle.main.infoDictionary ?? [:]
|
||||
return """
|
||||
StarPilot BT connection diagnostics
|
||||
\(ISO8601DateFormatter().string(from: Date()))
|
||||
App: \(info["CFBundleShortVersionString"] ?? "?") (\(info["CFBundleVersion"] ?? "?"))
|
||||
iOS: \(UIDevice.current.systemVersion)
|
||||
Mode: \(model.mode.title)
|
||||
Selected route: \(model.transport.label)
|
||||
LAN verified: \(model.lan.connected)
|
||||
Bluetooth verified: \(model.bluetooth.connected)
|
||||
Recent connection events:
|
||||
\(events.joined(separator: "\n"))
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
private struct DeveloperLogsView: View {
|
||||
@ObservedObject var model: AppModel
|
||||
@ObservedObject var log: ConnectionEventLog
|
||||
private func selectedReport() -> String {
|
||||
switch log.section {
|
||||
case "Galaxy": return model.galaxyPage.report(server: model.server, connection: model.transport.label)
|
||||
case "Live View": return model.diagnostics.diagnosticLog()
|
||||
default: return log.report(model: model)
|
||||
}
|
||||
}
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 18) {
|
||||
Text("Dev / Logs").font(.title2.bold())
|
||||
Text("Recent events stay in memory. Reports are shared only when you copy them.")
|
||||
.font(.subheadline).foregroundStyle(.secondary)
|
||||
Picker("Report", selection: $log.section) {
|
||||
ForEach(["Connections", "Galaxy", "Live View"], id: \.self) { Text($0).tag($0) }
|
||||
}.pickerStyle(.segmented)
|
||||
HStack {
|
||||
Button(log.copied ? "Copied" : "Copy report", systemImage: "doc.on.doc") {
|
||||
UIPasteboard.general.string = selectedReport(); log.copied = true
|
||||
}.buttonStyle(.borderedProminent).tint(.purple)
|
||||
Button("Refresh") { log.detail = selectedReport(); log.copied = false }.buttonStyle(.bordered)
|
||||
}
|
||||
Button("Copy all reports") {
|
||||
UIPasteboard.general.string = [log.report(model: model), model.galaxyPage.report(server: model.server, connection: model.transport.label), model.diagnostics.diagnosticLog(), "Galaxy screen updates\n" + model.assets.status].joined(separator: "\n\n")
|
||||
log.copied = true
|
||||
}
|
||||
Text(log.section == "Connections" ? log.report(model: model) : log.detail)
|
||||
.font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(14).background(Color(uiColor: .secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12))
|
||||
Button("Clear connection history") { log.clear(); log.detail = selectedReport() }
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}.padding(20)
|
||||
}.background(Color(uiColor: .systemBackground))
|
||||
.onAppear { log.detail = selectedReport() }
|
||||
.onChange(of: log.section) { _, _ in log.detail = selectedReport(); log.copied = false }
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
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
|
||||
/// GET one Galaxy page file (not an API call). Only the Wi-Fi/LAN transport can do this.
|
||||
func page(path: String) async throws -> BridgeResponse
|
||||
}
|
||||
|
||||
extension GalaxyRequestTransport {
|
||||
var catalogSHA256: String? { nil }
|
||||
func page(path: String) async throws -> BridgeResponse {
|
||||
throw BridgeError.message("Galaxy screens can only be downloaded from comma over Wi-Fi.")
|
||||
}
|
||||
}
|
||||
|
||||
/// When the phone already reaches comma over Wi-Fi/LAN it opens comma's two-minute pairing window itself, the same call
|
||||
/// as Pair phone on Galaxy's Bluetooth page, so nobody has to touch comma before the Bluetooth key claim.
|
||||
enum LANPairing {
|
||||
static let windowPath = "/api/bluetooth/action"
|
||||
static let windowBody = Data("{\"operation\":\"accept_pair\"}".utf8)
|
||||
@MainActor static func openWindow(over lan: any GalaxyRequestTransport) async -> Bool {
|
||||
guard lan.connected,
|
||||
let response = try? await lan.request(path: windowPath, method: "POST", headers: [:], body: windowBody) else { return false }
|
||||
return response.status == 200
|
||||
}
|
||||
}
|
||||
|
||||
enum SecretGoodGalaxy {
|
||||
static func validTarget(_ path: String) -> Bool {
|
||||
guard path.hasPrefix("/"), !path.hasPrefix("//"),
|
||||
let parts = URLComponents(string: path), parts.scheme == nil, parts.host == nil, parts.fragment == nil,
|
||||
let decoded = parts.percentEncodedPath.removingPercentEncoding,
|
||||
!decoded.contains("%"), !decoded.contains("\\"), !decoded.contains("//"),
|
||||
!decoded.unicodeScalars.contains(where: { $0.value < 32 }),
|
||||
!decoded.split(separator: "/").contains(where: { $0 == "." || $0 == ".." }) else { return false }
|
||||
return decoded.hasPrefix("/api/") || decoded == "/data/runtime.json"
|
||||
}
|
||||
/// A Galaxy page file under the same roots the app accepts when it saves comma's screens.
|
||||
static func validPage(_ path: String) -> Bool {
|
||||
guard path.hasPrefix("/"), path.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || [45, 46, 47, 95].contains($0) }) else { return false }
|
||||
let file = String(path.dropFirst())
|
||||
let parts = file.split(separator: "/", omittingEmptySubsequences: false)
|
||||
guard !parts.isEmpty, parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }), file != "data/runtime.json" else { return false }
|
||||
return ["index.html", "manifest.webmanifest", "sentry-push-worker.js"].contains(file)
|
||||
|| ["assets/", "css/", "js/", "vendor/", "data/"].contains(where: { file.hasPrefix($0) })
|
||||
}
|
||||
static func needsWiFi(_ path: String) -> Bool {
|
||||
let path = URLComponents(string: path)?.path ?? path
|
||||
return ["/api/recordings/", "/api/replay/", "/api/cameras/", "/api/maps/tiles/",
|
||||
"/api/starport/upload", "/api/starport/apk", "/api/phone-internet/", "/api/spotify/upload"].contains(where: { path.hasPrefix($0) })
|
||||
|| ["/api/auth/login", "/api/auth/logout"].contains(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Coalesce simultaneous identical reads. View/intent tokens are never cached for later use.
|
||||
@MainActor
|
||||
final class GalaxyReadCache: GalaxyRequestTransport {
|
||||
private let transport: any GalaxyRequestTransport
|
||||
private let sessionID: () -> String
|
||||
private var session = ""
|
||||
private var generation: UInt64 = 0
|
||||
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
|
||||
}
|
||||
|
||||
private func invalidate() {
|
||||
generation += 1
|
||||
// Already-sent reads still drain, but new reads cannot join an old one.
|
||||
pending.removeAll()
|
||||
}
|
||||
|
||||
func page(path: String) async throws -> BridgeResponse { try await transport.page(path: path) }
|
||||
|
||||
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)
|
||||
}
|
||||
guard body.isEmpty, path.hasPrefix("/api/"), headers.keys.allSatisfy({ !["authorization", "range"].contains($0.lowercased()) }) else {
|
||||
return try await transport.request(path: path, method: method, headers: headers, body: body)
|
||||
}
|
||||
let relevantHeaders = headers
|
||||
.map { "\($0.key.lowercased()):\($0.value)" }.sorted().joined(separator: "\n")
|
||||
let cacheKey = path + "\n" + relevantHeaders
|
||||
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
|
||||
guard readGeneration == generation, readSession == sessionID(), connected else {
|
||||
throw BridgeError.message("Connection or saved settings changed during this read. Load the page again.")
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
return response
|
||||
}
|
||||
}
|
||||
@@ -1,463 +0,0 @@
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
private struct GalaxyDownloadedFile: Identifiable {
|
||||
let id = UUID()
|
||||
let url: URL
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class GalaxyPageDiagnostics: ObservableObject {
|
||||
@Published fileprivate var downloadedFile: GalaxyDownloadedFile?
|
||||
@Published var downloadError: String?
|
||||
private var exportDirectory: URL?
|
||||
|
||||
fileprivate func offerDownload(_ url: URL) {
|
||||
exportDirectory = url.deletingLastPathComponent()
|
||||
downloadedFile = GalaxyDownloadedFile(url: url)
|
||||
record("Download ready to save or share")
|
||||
}
|
||||
func cleanUpDownload() {
|
||||
if let directory = exportDirectory { try? FileManager.default.removeItem(at: directory) }
|
||||
exportDirectory = nil
|
||||
}
|
||||
func downloadFailed(_ error: Error) {
|
||||
let value = error as NSError
|
||||
record("Download failed: \(value.domain) \(value.code)")
|
||||
downloadError = "The file couldn’t be downloaded. Please try again."
|
||||
}
|
||||
|
||||
var recover: ((Bool) -> Void)?
|
||||
@Published var darkAppearance: Bool?
|
||||
@Published var landscapeEditor = false
|
||||
@Published var copied = false
|
||||
@Published var stalled = false
|
||||
@Published var mounted = false
|
||||
@Published var reloadID = UUID()
|
||||
private(set) var started = Date()
|
||||
private(set) var events: [String] = []
|
||||
private var deadline: Task<Void, Never>?
|
||||
|
||||
func record(_ event: String) {
|
||||
events.append("\(ISO8601DateFormatter().string(from: Date())) \(event.prefix(300))")
|
||||
if events.count > 40 { events.removeFirst(events.count - 40) }
|
||||
}
|
||||
func begin() {
|
||||
deadline?.cancel()
|
||||
started = Date(); mounted = false; stalled = false; landscapeEditor = false
|
||||
record("Page loading")
|
||||
deadline = Task { [weak self] in
|
||||
do { try await Task.sleep(nanoseconds: 12_000_000_000) } catch { return }
|
||||
guard let self, !self.mounted else { return }
|
||||
self.record("No rendered Galaxy content after 12 seconds")
|
||||
self.stalled = true
|
||||
}
|
||||
}
|
||||
func rendered() {
|
||||
mounted = true; stalled = false; deadline?.cancel()
|
||||
record("Galaxy content rendered")
|
||||
}
|
||||
func fail(_ event: String) { record(event); mounted = false; stalled = true; deadline?.cancel() }
|
||||
func retry() { reloadID = UUID() }
|
||||
func report(server: LoopbackServer, connection: String) -> String {
|
||||
let info = Bundle.main.infoDictionary ?? [:]
|
||||
return """
|
||||
StarPilot BT Galaxy diagnostics
|
||||
\(ISO8601DateFormatter().string(from: Date()))
|
||||
App: \(info["CFBundleShortVersionString"] ?? "?") (\(info["CFBundleVersion"] ?? "?"))
|
||||
iOS: \(UIDevice.current.systemVersion)
|
||||
Connection: \(connection)
|
||||
Galaxy content rendered: \(mounted)
|
||||
Page age: \(Int(Date().timeIntervalSince(started))) seconds
|
||||
\(server.diagnosticSummary)
|
||||
Recent page events:
|
||||
\(events.joined(separator: "\n"))
|
||||
Recent local requests (no headers, query values or bodies):
|
||||
\(server.recentRequests.joined(separator: "\n"))
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
struct GalaxyWebView: View {
|
||||
let url: URL
|
||||
let requestKey: String
|
||||
@ObservedObject var diagnostics: GalaxyPageDiagnostics
|
||||
var isActive = true
|
||||
let report: () -> String
|
||||
var body: some View {
|
||||
ZStack {
|
||||
GalaxyPage(url: url, requestKey: requestKey, diagnostics: diagnostics, isActive: isActive)
|
||||
.id(url.absoluteString + diagnostics.reloadID.uuidString)
|
||||
if diagnostics.stalled {
|
||||
VStack(spacing: 16) {
|
||||
Image(systemName: "exclamationmark.bubble").font(.largeTitle).foregroundStyle(.purple)
|
||||
Text("Galaxy hasn’t loaded").font(.title2.bold())
|
||||
Text("Copy the report so we can find what failed, or try loading the page again.")
|
||||
.foregroundStyle(.secondary).multilineTextAlignment(.center)
|
||||
Button(diagnostics.copied ? "Report copied" : "Copy error report") {
|
||||
UIPasteboard.general.string = report(); diagnostics.copied = true
|
||||
}.buttonStyle(.borderedProminent).tint(.purple)
|
||||
Button("Retry Galaxy") { diagnostics.copied = false; diagnostics.recover?(false) }.buttonStyle(.bordered)
|
||||
}.padding(28).frame(maxWidth: 420)
|
||||
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 20)).padding(20)
|
||||
}
|
||||
}
|
||||
.sheet(item: $diagnostics.downloadedFile, onDismiss: diagnostics.cleanUpDownload) { file in
|
||||
GalaxyFileShareSheet(url: file.url) { diagnostics.downloadedFile = nil }
|
||||
}
|
||||
.alert("Couldn’t download file", isPresented: Binding(
|
||||
get: { diagnostics.downloadError != nil },
|
||||
set: { if !$0 { diagnostics.downloadError = nil } }
|
||||
)) {
|
||||
Button("OK", role: .cancel) { diagnostics.downloadError = nil }
|
||||
} message: { Text(diagnostics.downloadError ?? "") }
|
||||
}
|
||||
}
|
||||
|
||||
private struct GalaxyFileShareSheet: UIViewControllerRepresentable {
|
||||
let url: URL
|
||||
let finished: () -> Void
|
||||
func makeUIViewController(context: Context) -> UIActivityViewController {
|
||||
let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil)
|
||||
controller.completionWithItemsHandler = { _, _, _, _ in
|
||||
Task { @MainActor in finished() }
|
||||
}
|
||||
return controller
|
||||
}
|
||||
func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}
|
||||
}
|
||||
|
||||
private struct GalaxyPage: UIViewRepresentable {
|
||||
let url: URL
|
||||
let requestKey: String
|
||||
|
||||
let diagnostics: GalaxyPageDiagnostics
|
||||
let isActive: Bool
|
||||
func makeCoordinator() -> Coordinator {
|
||||
let coordinator = Coordinator(origin: url, diagnostics: diagnostics)
|
||||
coordinator.isVisible = isActive
|
||||
return coordinator
|
||||
}
|
||||
|
||||
func makeUIView(context: Context) -> WKWebView {
|
||||
let config = WKWebViewConfiguration()
|
||||
config.allowsInlineMediaPlayback = true
|
||||
config.defaultWebpagePreferences.allowsContentJavaScript = true
|
||||
diagnostics.begin()
|
||||
config.userContentController.add(context.coordinator, name: "galaxyDiagnostics")
|
||||
let script = """
|
||||
(() => {
|
||||
if (location.origin !== '\(url.scheme!)://\(url.host!):\(url.port!)') return;
|
||||
window.__galaxyNative = true;
|
||||
const phoneAppearance = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const syncTheme = () => {
|
||||
const theme = phoneAppearance.matches ? 'dark' : 'light';
|
||||
localStorage.setItem('galaxy-preview-theme', theme);
|
||||
document.documentElement.dataset.theme = theme;
|
||||
};
|
||||
syncTheme();
|
||||
phoneAppearance.addEventListener('change', () => {
|
||||
const dark = phoneAppearance.matches;
|
||||
if ((document.documentElement.dataset.theme === 'dark') !== dark) {
|
||||
document.querySelector('.gx-theme-toggle')?.click();
|
||||
}
|
||||
syncTheme();
|
||||
});
|
||||
const reportTheme = () => {
|
||||
const theme = document.documentElement?.dataset.theme;
|
||||
if (theme !== 'dark' && theme !== 'light') return;
|
||||
try { window.webkit.messageHandlers.galaxyDiagnostics.postMessage({kind: 'theme', dark: theme === 'dark'}); } catch (_) {}
|
||||
};
|
||||
const watchTheme = () => {
|
||||
if (!document.documentElement) return;
|
||||
new MutationObserver(reportTheme).observe(document.documentElement, {attributes: true, attributeFilter: ['data-theme']});
|
||||
reportTheme();
|
||||
};
|
||||
if (document.documentElement) watchTheme();
|
||||
else document.addEventListener('DOMContentLoaded', watchTheme, {once: true});
|
||||
let nativeVisible = \(isActive ? "true" : "false");
|
||||
Object.defineProperty(document, 'visibilityState', {configurable: true, get: () => nativeVisible ? 'visible' : 'hidden'});
|
||||
Object.defineProperty(document, 'hidden', {configurable: true, get: () => !nativeVisible});
|
||||
window.__galaxySetVisible = visible => {
|
||||
if (nativeVisible === !!visible) return;
|
||||
nativeVisible = !!visible;
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
};
|
||||
const emit = (kind, path = '', code = 0) => {
|
||||
try { window.webkit.messageHandlers.galaxyDiagnostics.postMessage({kind, path, code}); } catch (_) {}
|
||||
};
|
||||
// Keep this native presentation independent of downloaded Galaxy assets.
|
||||
const editorScreen = matchMedia('(orientation: landscape) and (max-height: 600px)');
|
||||
let editorFocused = false;
|
||||
const editorCSS = document.createElement('style');
|
||||
editorCSS.textContent = `
|
||||
html.native-layout-editor .blur-nav,
|
||||
html.native-layout-editor .gx-appbar__pill,
|
||||
html.native-layout-editor .gx-appbar__menu,
|
||||
html.native-layout-editor .gx-layout > .gx-page-header { display: none !important; }
|
||||
html.native-layout-editor .gx-app { animation: none; }
|
||||
html.native-layout-editor .gx-appbar {
|
||||
position: fixed; inset: max(4px, env(safe-area-inset-top)) auto auto max(8px, env(safe-area-inset-left));
|
||||
width: 44px; padding: 0; margin: 0; z-index: 20;
|
||||
}
|
||||
html.native-layout-editor .gx-appbar__back { width: 44px; height: 44px; min-width: 44px; min-height: 44px; }
|
||||
html.native-layout-editor .gx-content {
|
||||
max-width: none; padding: max(4px, env(safe-area-inset-top)) max(8px, env(safe-area-inset-right)) max(8px, env(safe-area-inset-bottom)) max(8px, env(safe-area-inset-left));
|
||||
}
|
||||
html.native-layout-editor .gx-layout { --layout-sticky-top: max(4px, env(safe-area-inset-top)); display: grid; gap: 6px; }
|
||||
html.native-layout-editor .gx-layout__savebar {
|
||||
grid-row: 1; margin-left: 52px; padding: 0 4px 0 10px; min-height: 44px; gap: 4px;
|
||||
}
|
||||
html.native-layout-editor .gx-layout__savebar .gx-btn { min-height: 44px; padding-inline: 12px; }
|
||||
html.native-layout-editor .gx-layout__targets { grid-row: 2; margin: 0; gap: 8px; }
|
||||
html.native-layout-editor .gx-layout__targets .gx-btn { min-height: 44px; padding: 4px 12px; }
|
||||
html.native-layout-editor .gx-layout__workspace { gap: 8px; grid-template-columns: minmax(0, 1.35fr) minmax(260px, 1fr); }
|
||||
html.native-layout-editor .gx-layout__preview-card { padding: 4px; gap: 4px; }
|
||||
html.native-layout-editor .gx-layout__preview-card > p.gx-note:not([role]) { display: none; }
|
||||
html.native-layout-editor .gx-layout__preview-card .gx-layout__preview {
|
||||
width: auto; max-width: 100%; max-height: calc(100svh - 200px - env(safe-area-inset-top) - env(safe-area-inset-bottom)); margin-inline: auto;
|
||||
}
|
||||
html.native-layout-editor .gx-layout__inspector {
|
||||
padding: 8px; gap: 8px; max-height: calc(100svh - 124px - env(safe-area-inset-top) - env(safe-area-inset-bottom)); overflow: auto;
|
||||
}
|
||||
html.native-layout-editor .gx-layout__sections { margin: -8px -8px 0; padding: 4px; gap: 2px; top: -8px; }
|
||||
html.native-layout-editor .gx-layout__sections .gx-btn { min-height: 44px; padding: 4px 8px; white-space: nowrap; }
|
||||
`;
|
||||
const syncEditor = () => {
|
||||
const focused = editorScreen.matches && !!document.querySelector('.gx-layout');
|
||||
if (focused === editorFocused) return;
|
||||
editorFocused = focused;
|
||||
document.documentElement.classList.toggle('native-layout-editor', focused);
|
||||
try { window.webkit.messageHandlers.galaxyDiagnostics.postMessage({kind: 'editorFocus', active: focused}); } catch (_) {}
|
||||
};
|
||||
const startEditorPresentation = () => {
|
||||
document.head.appendChild(editorCSS);
|
||||
new MutationObserver(syncEditor).observe(document.body, {childList: true, subtree: true});
|
||||
editorScreen.addEventListener('change', syncEditor);
|
||||
syncEditor();
|
||||
};
|
||||
document.addEventListener('DOMContentLoaded', startEditorPresentation, {once: true});
|
||||
const pathOnly = value => {
|
||||
try { return new URL(value, location.href).pathname; } catch (_) { return ''; }
|
||||
};
|
||||
window.addEventListener('error', event => {
|
||||
if (event.target && event.target !== window) {
|
||||
emit('resource', pathOnly(event.target.src || event.target.href || ''));
|
||||
} else { emit('script', pathOnly(event.filename || ''), event.lineno || 0); }
|
||||
}, true);
|
||||
window.addEventListener('unhandledrejection', () => emit('promise'));
|
||||
let rendered = false;
|
||||
const checkContent = () => {
|
||||
const root = document.querySelector('#galaxy-app');
|
||||
if (root && !root.hasAttribute('v-cloak') && root.children.length && root.innerText.trim().length) {
|
||||
if (!rendered) { rendered = true; emit('rendered'); }
|
||||
} else if (rendered) { rendered = false; emit('blank'); }
|
||||
};
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
checkContent(); setInterval(checkContent, 1000);
|
||||
}, {once: 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 })).then(async response => {
|
||||
if (response.status === 501) {
|
||||
const message = await response.clone().json().catch(() => null);
|
||||
let notice = document.getElementById('native-wifi-notice');
|
||||
if (!notice) {
|
||||
notice = document.createElement('button'); notice.id = 'native-wifi-notice';
|
||||
notice.setAttribute('role', 'status');
|
||||
notice.style.cssText = 'position:fixed;top:12px;left:12px;right:12px;z-index:10000;padding:16px;border-radius:16px;background:Canvas;color:CanvasText;border:1px solid currentColor;font:inherit;';
|
||||
notice.onclick = () => notice.remove(); document.body.appendChild(notice);
|
||||
}
|
||||
notice.textContent = typeof message?.error === 'string' ? message.error : 'Connect to comma over Wi-Fi for this feature.';
|
||||
}
|
||||
return response;
|
||||
});
|
||||
};
|
||||
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) {
|
||||
context.coordinator.isVisible = isActive
|
||||
context.coordinator.syncVisibility(uiView)
|
||||
}
|
||||
static func dismantleUIView(_ uiView: WKWebView, coordinator: Coordinator) {
|
||||
uiView.configuration.userContentController.removeScriptMessageHandler(forName: "galaxyDiagnostics")
|
||||
uiView.navigationDelegate = nil; uiView.uiDelegate = nil
|
||||
coordinator.cancelDownloads()
|
||||
uiView.stopLoading()
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, WKDownloadDelegate {
|
||||
private var downloads: [ObjectIdentifier: (WKDownload, URL?)] = [:]
|
||||
var isVisible = true
|
||||
func syncVisibility(_ webView: WKWebView) {
|
||||
webView.evaluateJavaScript("window.__galaxySetVisible?.(\(isVisible ? "true" : "false"))", completionHandler: nil)
|
||||
}
|
||||
let origin: URL
|
||||
let diagnostics: GalaxyPageDiagnostics
|
||||
init(origin: URL, diagnostics: GalaxyPageDiagnostics) { self.origin = origin; self.diagnostics = diagnostics }
|
||||
|
||||
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||
let frame = message.frameInfo.securityOrigin
|
||||
guard frame.protocol == origin.scheme, frame.host == origin.host, frame.port == origin.port,
|
||||
let body = message.body as? [String: Any], let kind = body["kind"] as? String else { return }
|
||||
let path = LoopbackServer.reportPath(body["path"] as? String ?? "")
|
||||
switch kind {
|
||||
case "theme":
|
||||
if message.frameInfo.isMainFrame, let dark = body["dark"] as? Bool {
|
||||
diagnostics.darkAppearance = dark
|
||||
let background = dark ? UIColor(red: 0.06, green: 0.05, blue: 0.09, alpha: 1) : .systemBackground
|
||||
message.webView?.backgroundColor = background
|
||||
message.webView?.scrollView.backgroundColor = background
|
||||
}
|
||||
case "editorFocus":
|
||||
if message.frameInfo.isMainFrame, let active = body["active"] as? Bool {
|
||||
diagnostics.landscapeEditor = active
|
||||
}
|
||||
case "rendered": if message.frameInfo.isMainFrame { diagnostics.rendered() }
|
||||
case "blank": if message.frameInfo.isMainFrame { diagnostics.begin() }
|
||||
case "resource": diagnostics.record("Resource failed: \(path)")
|
||||
case "script": diagnostics.record("JavaScript error: \(path), line \(body["code"] as? Int ?? 0)")
|
||||
case "promise": diagnostics.record("Unhandled JavaScript promise rejection")
|
||||
case "search":
|
||||
if let phase = body["phase"] as? String, ["started", "results", "partial", "ready"].contains(phase),
|
||||
let count = body["count"] as? Int, (0...50_000).contains(count) {
|
||||
diagnostics.record("Toggle search \(phase): \(count) settings indexed")
|
||||
}
|
||||
default: break
|
||||
}
|
||||
}
|
||||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||||
syncVisibility(webView)
|
||||
diagnostics.record("HTML navigation finished; waiting for Galaxy content")
|
||||
}
|
||||
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
||||
navigationFailed(error)
|
||||
}
|
||||
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { navigationFailed(error) }
|
||||
private func navigationFailed(_ error: Error) {
|
||||
let value = error as NSError
|
||||
if !downloads.isEmpty, value.code == NSURLErrorCancelled || (value.domain == "WKErrorDomain" && value.code == 102) { return }
|
||||
if value.domain == NSURLErrorDomain && value.code == NSURLErrorCancelled { return }
|
||||
diagnostics.fail("Navigation failed: \(value.domain) \(value.code)")
|
||||
if isVisible, value.domain == NSURLErrorDomain,
|
||||
[NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost].contains(value.code) {
|
||||
diagnostics.recover?(true)
|
||||
}
|
||||
}
|
||||
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||||
diagnostics.fail("Galaxy web content process terminated")
|
||||
if isVisible { diagnostics.recover?(true) }
|
||||
}
|
||||
|
||||
|
||||
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(action.shouldPerformDownload ? .download : .allow)
|
||||
} else if url.scheme == "blob" {
|
||||
let frame = action.sourceFrame.securityOrigin
|
||||
guard frame.protocol == origin.scheme, frame.host == origin.host,
|
||||
frame.port == origin.port else { decisionHandler(.cancel); return }
|
||||
decisionHandler(action.shouldPerformDownload ? .download : .allow)
|
||||
} else if url.scheme == "about" {
|
||||
decisionHandler(.allow)
|
||||
} else {
|
||||
if action.navigationType == .linkActivated, ["https", "http"].contains(url.scheme ?? "") {
|
||||
UIApplication.shared.open(url)
|
||||
}
|
||||
decisionHandler(.cancel)
|
||||
}
|
||||
}
|
||||
|
||||
func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) {
|
||||
track(download)
|
||||
}
|
||||
func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
|
||||
track(download)
|
||||
}
|
||||
private func track(_ download: WKDownload) {
|
||||
guard downloads.isEmpty, diagnostics.downloadedFile == nil else {
|
||||
download.cancel { _ in }
|
||||
return
|
||||
}
|
||||
downloads[ObjectIdentifier(download)] = (download, nil)
|
||||
download.delegate = self
|
||||
diagnostics.record("File download started")
|
||||
}
|
||||
func download(_ download: WKDownload, decideDestinationUsing response: URLResponse,
|
||||
suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
|
||||
let id = ObjectIdentifier(download)
|
||||
guard downloads[id] != nil else { completionHandler(nil); return }
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let name = (suggestedFilename as NSString).lastPathComponent
|
||||
let safeName = name.isEmpty || name == "." || name == ".." ? "toggle-backup.json" : name
|
||||
let destination = directory.appendingPathComponent(safeName)
|
||||
downloads[id] = (download, destination)
|
||||
completionHandler(destination)
|
||||
} catch {
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
completionHandler(nil)
|
||||
diagnostics.downloadFailed(error)
|
||||
}
|
||||
}
|
||||
func downloadDidFinish(_ download: WKDownload) {
|
||||
guard let (_, destination) = downloads.removeValue(forKey: ObjectIdentifier(download)),
|
||||
let destination else { return }
|
||||
diagnostics.offerDownload(destination)
|
||||
}
|
||||
func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
|
||||
if let (_, destination) = downloads.removeValue(forKey: ObjectIdentifier(download)),
|
||||
let destination {
|
||||
try? FileManager.default.removeItem(at: destination.deletingLastPathComponent())
|
||||
}
|
||||
diagnostics.downloadFailed(error)
|
||||
}
|
||||
func cancelDownloads() {
|
||||
let active = downloads.values
|
||||
downloads.removeAll()
|
||||
for (download, destination) in active {
|
||||
download.delegate = nil
|
||||
download.cancel { _ in }
|
||||
if let destination { try? FileManager.default.removeItem(at: destination.deletingLastPathComponent()) }
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
struct LocalRequest {
|
||||
let method: String
|
||||
let target: String
|
||||
let headers: [String: String]
|
||||
let body: Data
|
||||
|
||||
// Package uploads stay on LAN; ordinary requests retain the Bluetooth-sized limit.
|
||||
static let maxPackageBody = 256 * 1024 * 1024
|
||||
|
||||
static func isPackageUpload(method: String, target: String) -> Bool {
|
||||
method == "POST" && ["/api/starport/upload", "/api/spotify/upload"].contains(target)
|
||||
}
|
||||
|
||||
static func bodyLimit(method: String, target: String) -> Int {
|
||||
isPackageUpload(method: method, target: target) ? maxPackageBody : Wire.maxBody
|
||||
}
|
||||
|
||||
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 <= bodyLimit(method: String(first[0]), target: String(first[1])) 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)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user