mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-01 21:33:41 +08:00
update galaxy support, connections and parked sentry alerts
This commit is contained in:
@@ -63,7 +63,7 @@ No docs build, sync, or network lookup is required; update this file when a wiki
|
||||
| Maps | Local map status and a parked catalog-region download, progress, or cancellation. A completed selection takes effect at the next map service start. |
|
||||
| Cameras and Sentry | Saved PiP and V-ASM settings and bounded Sentry event metadata. The crop editor uses a browser-local still image; it does not upload that image. |
|
||||
| Sound packs | Catalog status, verified download and cancellation through the local sound owner. |
|
||||
| Galaxy Access & Install | Remote link pairing, Galaxy installation, and an opt-in Wi-Fi hotspot. Local addresses are on Home. |
|
||||
| Galaxy Access & Connections | Remote link pairing, Galaxy installation, Networks, Bluetooth, and support. Local addresses are on Home. |
|
||||
|
||||
`Refresh` and branch changes request filtered
|
||||
history metadata in a separate Git cache and worker. They remain available during
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Capture the USB and Bluetooth input inventory without opening any event device."""
|
||||
|
||||
from base64 import b64encode
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
import secrets
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from openpilot.starpilot.controllers import input as controller_input
|
||||
|
||||
|
||||
def controller_input_report():
|
||||
"""Include interfaces filtered out of Attached Controllers and mask device names per report."""
|
||||
devices = []
|
||||
groups = {}
|
||||
salt = secrets.token_bytes(8)
|
||||
truncated = False
|
||||
for entry in sorted(controller_input.SYS_ROOT.iterdir()):
|
||||
if not controller_input.EVENT_NAME.fullmatch(entry.name):
|
||||
continue
|
||||
device = entry / 'device'
|
||||
match = controller_input.MODALIAS.match(controller_input._text(device / 'modalias'))
|
||||
if match is None or int(match[1], 16) not in controller_input.EXTERNAL_BUSES:
|
||||
continue
|
||||
if len(devices) == controller_input.MAX_CANDIDATES:
|
||||
truncated = True
|
||||
break
|
||||
node = controller_input.DEV_ROOT / entry.name
|
||||
identity = controller_input._inspect(node)
|
||||
if identity is not None:
|
||||
groups.setdefault(identity.device_id, []).append(entry.name)
|
||||
name = controller_input._text(device / 'name')
|
||||
devices.append({
|
||||
'event': entry.name,
|
||||
'name': f'masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}' if name else '',
|
||||
'inputId': match[0],
|
||||
'properties': controller_input._text(device / 'properties'),
|
||||
'capabilities': {key: controller_input._text(device / 'capabilities' / key) for key in ('ev', 'key', 'rel', 'abs')},
|
||||
'discovery': 'eligible' if identity else 'filtered',
|
||||
'eventNodePresent': node.exists(),
|
||||
})
|
||||
duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events}
|
||||
for row in devices:
|
||||
if row['event'] in duplicates:
|
||||
row.update(discovery='duplicate identity', matchingEvents=duplicates[row['event']])
|
||||
return {'externalInputInterfaces': devices, 'truncated': truncated}
|
||||
|
||||
|
||||
def controller_capture():
|
||||
report = {'schemaVersion': 1, 'capturedAt': datetime.now(timezone.utc).isoformat(timespec='seconds'), **controller_input_report()}
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('bluetooth-log.json', json.dumps(report, indent=2) + '\n')
|
||||
return {'schemaVersion': 1, 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
@@ -246,7 +246,7 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
|
||||
if cookie is not None:
|
||||
self.send_header('Set-Cookie', cookie)
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/")
|
||||
self.end_headers()
|
||||
if self.command != 'HEAD':
|
||||
self.wfile.write(body)
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
"""Actual LAN addresses for direct Galaxy access, independent of the tunnel."""
|
||||
|
||||
from base64 import b64encode
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timezone
|
||||
from ipaddress import IPv4Address, ip_network
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
|
||||
LAN = tuple(ip_network(value) for value in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16'))
|
||||
@@ -73,3 +79,158 @@ class LocalAccess:
|
||||
'reason': '' if addresses else reason}
|
||||
self.expiry = self.clock() + 5.0
|
||||
return self.cached
|
||||
|
||||
|
||||
DISCOVERY_UNIT = 'galaxy-lan-discovery.service'
|
||||
DISCOVERY_MESSAGE = re.compile(
|
||||
r'(Galaxy Wi-Fi discovery available on [0-9]{1,3} local interface\(s\)|'
|
||||
r'Wi-Fi discovery unavailable: [A-Za-z][A-Za-z0-9_]{0,63}|LAN publisher cleanup failed)\Z',
|
||||
)
|
||||
|
||||
|
||||
BLE_UNIT = 'galaxy-ble-fork.service'
|
||||
BLE_MESSAGE = re.compile(
|
||||
r'(Pairing credentials changed; [0-9]{1,4} phone\(s\) paired|Phone claimed pairing window|'
|
||||
r'Galaxy BLE handshake challenge requested; active sessions=[0-9]{1,4}|'
|
||||
r'Rejected invalid or unauthenticated BLE message|Notification transfer interrupted \([A-Za-z0-9_]{1,64}\); reconnect to check request outcome|'
|
||||
r'BLE advertisement released by BlueZ; bridge will re-register after restart|Registering Galaxy BLE advertisement|'
|
||||
r'Starting Galaxy bridge pid=[0-9]{1,10} source=[0-9a-f]{12}|'
|
||||
r'Galaxy BLE bridge ready on /org/bluez/hci[0-9]{1,3}; forwarding to localhost:[0-9]{1,5}|'
|
||||
r'Stopping Galaxy bridge; clearing ready status and Bluetooth sessions)\Z',
|
||||
)
|
||||
INTERFACE_NAME = re.compile(r'[A-Za-z0-9_.:-]{1,32}\Z')
|
||||
|
||||
|
||||
def _network_inventory(run):
|
||||
lines = []
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'address', 'show'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid network inventory')
|
||||
for row in rows[:64]:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = row.get('ifname')
|
||||
if not isinstance(name, str) or not INTERFACE_NAME.fullmatch(name):
|
||||
continue
|
||||
state = row.get('operstate')
|
||||
if state not in ('UNKNOWN', 'NOTPRESENT', 'DOWN', 'LOWERLAYERDOWN', 'TESTING', 'DORMANT', 'UP'):
|
||||
state = 'unknown'
|
||||
flags = row.get('flags', [])
|
||||
if not isinstance(flags, list):
|
||||
flags = []
|
||||
flags = ','.join(flag for flag in ('UP', 'LOWER_UP', 'RUNNING', 'MULTICAST', 'LOOPBACK') if flag in flags)
|
||||
addresses = []
|
||||
info_rows = row.get('addr_info', [])
|
||||
for info in info_rows[:16] if isinstance(info_rows, list) else []:
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
try:
|
||||
address, prefix = IPv4Address(info.get('local')), info.get('prefixlen')
|
||||
except ValueError:
|
||||
continue
|
||||
if any(address in network for network in LAN) and type(prefix) is int and 0 <= prefix <= 32:
|
||||
addresses.append(f'{address}/{prefix}')
|
||||
lines.append(f'{name}: state={state}; flags={flags or "none"}; private IPv4={", ".join(addresses) or "none"}')
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('Network interface inventory unavailable')
|
||||
try:
|
||||
result = run(['ip', '-j', '-4', 'route', 'show', 'default'], capture_output=True, timeout=1, check=True)
|
||||
rows = json.loads(result.stdout) if len(result.stdout) <= 65536 else None
|
||||
if not isinstance(rows, list):
|
||||
raise ValueError('Invalid route inventory')
|
||||
interfaces = [row['dev'] for row in rows[:16] if isinstance(row, dict)
|
||||
and isinstance(row.get('dev'), str) and INTERFACE_NAME.fullmatch(row['dev'])]
|
||||
lines.append('IPv4 default route interfaces: ' + (', '.join(interfaces) or 'none'))
|
||||
except (OSError, subprocess.SubprocessError, ValueError):
|
||||
lines.append('IPv4 default route inventory unavailable')
|
||||
try:
|
||||
result = run(['ss', '-H', '-lnt', 'sport = :8082'], capture_output=True, timeout=1, check=True)
|
||||
bindings = set()
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:32]:
|
||||
fields = line.split()
|
||||
if len(fields) < 5 or fields[0] != 'LISTEN' or not fields[3].endswith(':8082'):
|
||||
continue
|
||||
host = fields[3][:-5]
|
||||
if host in ('*', '0.0.0.0', '[::]'):
|
||||
bindings.add('all interfaces')
|
||||
elif host.startswith('127.') or host == '[::1]':
|
||||
bindings.add('loopback')
|
||||
else:
|
||||
bindings.add('specific interface')
|
||||
lines.append('TCP port 8082 listening: ' + (', '.join(sorted(bindings)) or 'no'))
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('TCP port 8082 listener state unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def _service_capture(run, unit, pattern, label):
|
||||
state = 'unavailable'
|
||||
details = []
|
||||
try:
|
||||
result = run(['systemctl', 'show', unit, '--property=ActiveState,SubState,Result,NRestarts,ExecMainStatus'],
|
||||
capture_output=True, timeout=1, check=True)
|
||||
for line in result.stdout.decode('ascii', errors='replace').splitlines()[:12]:
|
||||
if re.fullmatch(r'(?:ActiveState|SubState|Result)=[a-z][a-z0-9-]{0,39}|(?:NRestarts|ExecMainStatus)=[0-9]{1,10}', line):
|
||||
if line.startswith('ActiveState='):
|
||||
state = line.split('=', 1)[1]
|
||||
else:
|
||||
details.append(line)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
lines = [f'{label}: {state}', *details, 'Recent service events (last 2 hours, up to 120 journal records read)']
|
||||
try:
|
||||
result = run(['journalctl', '--no-pager', '--quiet', '-u', unit, '--since', '-2h',
|
||||
'-n', '120', '-o', 'json', '--output-fields=MESSAGE'],
|
||||
capture_output=True, timeout=2, check=True)
|
||||
events = []
|
||||
for raw in result.stdout.splitlines()[-120:]:
|
||||
if len(raw) > 8192:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
message = entry.get('MESSAGE') if isinstance(entry, dict) else None
|
||||
if isinstance(message, str) and pattern.fullmatch(message):
|
||||
stamp = entry.get('__REALTIME_TIMESTAMP', '')
|
||||
if isinstance(stamp, str) and re.fullmatch(r'[0-9]{1,16}', stamp):
|
||||
timestamp = datetime.fromtimestamp(int(stamp) / 1e6, timezone.utc).isoformat(timespec='seconds')
|
||||
message = f'{timestamp} {message}'
|
||||
events.append(message)
|
||||
except (ValueError, OSError, OverflowError):
|
||||
continue
|
||||
lines.extend(events or ['No matching events'])
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
lines.append('Advertiser journal unavailable' if unit == DISCOVERY_UNIT else 'BLE journal unavailable')
|
||||
return lines
|
||||
|
||||
|
||||
def connection_capture(addresses, *, configuration_allowed=None, run=subprocess.run):
|
||||
lines = ['StarPilot connection capture', 'Capture schema: 2',
|
||||
f'Captured at (UTC): {datetime.now(timezone.utc).isoformat(timespec="seconds")}',
|
||||
'Galaxy endpoint: HTTP port 8082', 'Bonjour service: _sp-galaxy._tcp.local.']
|
||||
try:
|
||||
with open('/proc/uptime') as stream:
|
||||
lines.append(f'Comma uptime: {float(stream.read(128).split()[0]):.0f} seconds')
|
||||
except (OSError, ValueError, IndexError):
|
||||
lines.append('Comma uptime: unavailable')
|
||||
if configuration_allowed is not None:
|
||||
try:
|
||||
lines.append(f'Parked configuration allowed: {bool(configuration_allowed())}')
|
||||
except Exception:
|
||||
lines.append('Parked configuration allowed: unavailable')
|
||||
lines.extend(['', 'Advertisable local addresses'])
|
||||
lines.extend(f'{row["interface"]}: {row["url"]}' for row in addresses['addresses'])
|
||||
if not addresses['available']:
|
||||
lines.append(addresses['reason'] or 'No eligible local address')
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
network = pool.submit(_network_inventory, run)
|
||||
discovery = pool.submit(_service_capture, run, DISCOVERY_UNIT, DISCOVERY_MESSAGE, 'Bonjour advertiser')
|
||||
bluetooth = pool.submit(_service_capture, run, BLE_UNIT, BLE_MESSAGE, 'Bluetooth bridge')
|
||||
lines.extend(['', 'Network interfaces', *network.result(), '', *discovery.result(), '', *bluetooth.result()])
|
||||
report = '\n'.join(lines) + '\n'
|
||||
output = BytesIO()
|
||||
with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive:
|
||||
archive.writestr('connection-logs.txt', report)
|
||||
# Keep the original text field for browsers still running the previous page.
|
||||
return {'schemaVersion': 1, 'text': report[:16384], 'zipBase64': b64encode(output.getvalue()).decode('ascii')}
|
||||
|
||||
@@ -51,7 +51,7 @@ from openpilot.starpilot.ui.layout_preview_transport import (request_profile)
|
||||
from openpilot.starpilot.favorites.owner import FavoritesChanged
|
||||
from openpilot.starpilot.galaxy.favorites import FavoritesGateway
|
||||
from openpilot.starpilot.galaxy.system_monitor import SystemMonitor
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive
|
||||
from openpilot.starpilot.galaxy.vehicle_selection import VehicleSelectionChanged, VehicleSelectionGateway, VehicleSelectionUnverified
|
||||
from openpilot.starpilot.bluetooth.owner import BluetoothOwner, BluetoothRejected, BluetoothUnavailable, normalized_address
|
||||
@@ -186,6 +186,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
summary_lock = threading.Lock()
|
||||
motion_events = sentry_events if sentry_events is not None else SentryEvents()
|
||||
sentry_events_lock = threading.Lock()
|
||||
simulation_busy = threading.Event()
|
||||
last_simulation = [float("-inf")]
|
||||
notification_owner = notifications
|
||||
snapshots = camera_snapshot if camera_snapshot is not None else CameraSnapshot()
|
||||
@@ -693,9 +694,11 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return False
|
||||
|
||||
def settings_session(self):
|
||||
token = self.session_token()
|
||||
return self.current_settings_session(self.session_token(), self.direct_local())
|
||||
|
||||
def current_settings_session(self, token, direct_local):
|
||||
with session_lock:
|
||||
if self.direct_local() and sessions.valid(token, local_generation):
|
||||
if direct_local and sessions.valid(token, local_generation):
|
||||
return token, local_generation
|
||||
generation = access.current_generation()
|
||||
if getattr(self.server, 'remote_transport', False):
|
||||
@@ -954,7 +957,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
return
|
||||
from openpilot.starpilot.galaxy.pairing_ready import bridge_state, pairing_readiness
|
||||
self.json(200, pairing_readiness(parked=configuration_allowed, snapshot=lambda: bluetooth_owner().snapshot(), bridge=bridge_state))
|
||||
elif path in ('/api/local-access', '/api/tmux/live', '/api/troubleshoot'):
|
||||
elif path in ('/api/local-access', '/api/local-access/capture', '/api/controllers/log/capture', '/api/tmux/live', '/api/troubleshoot'):
|
||||
if not self.require_session():
|
||||
return
|
||||
identity = self.settings_session()
|
||||
@@ -964,6 +967,11 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
try:
|
||||
if path == '/api/local-access':
|
||||
result = address_source.snapshot()
|
||||
elif path == '/api/local-access/capture':
|
||||
result = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
|
||||
elif path == '/api/controllers/log/capture':
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
result = controller_capture()
|
||||
elif path == '/api/tmux/live':
|
||||
result = console_source.snapshot()
|
||||
else:
|
||||
@@ -1090,7 +1098,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
except ValueError:
|
||||
route_key = ''
|
||||
try:
|
||||
result = navigation_owner().snapshot(route_key if re.fullmatch(r'[0-9a-f]{16}', route_key) else None)
|
||||
result = navigation_owner().snapshot(route_key if re.fullmatch(r'[0-9a-hjkmnp-tv-z]{12}', route_key) else None)
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
self.json(503, {'error': 'Navigation status is unavailable'})
|
||||
else:
|
||||
@@ -1457,7 +1465,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(400, {'error': 'Choose an event image'})
|
||||
return
|
||||
try:
|
||||
body = motion_events.image(parts[0], parts[1])
|
||||
body = notification_owner.test_image(parts[0]) if parts[1] == 'test' else motion_events.image(parts[0], parts[1])
|
||||
if body is None:
|
||||
raise SentryEventsUnavailable
|
||||
except SentryEventsUnavailable:
|
||||
self.json(404, {'error': 'Event image unavailable'})
|
||||
else:
|
||||
@@ -1743,7 +1753,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', '/api/galaxy/networks',
|
||||
'/api/cameras/snapshot', '/api/cameras/white-balance',
|
||||
'/api/starport/layout', '/api/starport/enable', '/api/starport/control', '/api/starport/pairing',
|
||||
'/api/starport/logs/send',
|
||||
'/api/starport/logs/send', '/api/companion/support-ticket',
|
||||
'/api/starport/pairing/response', '/api/starport/pairing/cancel', '/api/starport/pairing/select',
|
||||
'/api/spotify/enable', '/api/spotify/key', '/api/spotify/preferences', '/api/spotify/control', '/api/spotify/maintenance',
|
||||
'/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots',
|
||||
@@ -1753,7 +1763,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
||||
'/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/events/delete', '/api/crash-reports/delete',
|
||||
'/api/recordings/delete-videos', '/api/sentry/notifications', '/api/sentry/notifications/photo-test', '/api/sentry/events/delete', '/api/crash-reports/delete',
|
||||
'/api/navigation/search', '/api/navigation/action', '/api/navigation/offline', '/api/drive-state/action',
|
||||
'/api/toyota-tools/action', '/api/vehicle-selection/preview', '/api/vehicle-selection/confirm'):
|
||||
self.json(405, {'error': 'Method unavailable'})
|
||||
@@ -1817,6 +1827,51 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
else:
|
||||
self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/companion/support-ticket':
|
||||
import requests
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if (not isinstance(payload, dict) or not isinstance(payload.get('code'), str) or
|
||||
not re.fullmatch(r'[0-9a-f]{16}', payload['code']) or payload.get('action') not in ('check', 'send')):
|
||||
self.json(400, {'error': 'Enter the code from the Discord request.'})
|
||||
return
|
||||
relay = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/device'
|
||||
def relay_post(body):
|
||||
response = requests.post(relay, json=body, allow_redirects=False, timeout=(5, 30))
|
||||
if response.status_code == 410:
|
||||
raise LookupError()
|
||||
response.raise_for_status()
|
||||
if response.status_code != 200:
|
||||
raise ValueError()
|
||||
return response.json()
|
||||
try:
|
||||
code = payload['code']
|
||||
ticket = relay_post({'action': 'check', 'code': code})
|
||||
kind = ticket['kind']
|
||||
if kind not in ('controller', 'connection'):
|
||||
raise ValueError()
|
||||
if payload['action'] == 'check':
|
||||
self.json(200, {'kind': kind, 'title': ticket['title']})
|
||||
return
|
||||
if kind == 'controller':
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
capture = controller_capture()
|
||||
else:
|
||||
capture = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
|
||||
if self.settings_session() != identity:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
result = relay_post({'action': 'send', 'code': code, 'archive': capture['zipBase64']})
|
||||
if result.get('sent') is not True:
|
||||
raise ValueError()
|
||||
self.json(200, {'sent': True})
|
||||
except LookupError:
|
||||
self.json(410, {'error': 'Code expired or incorrect. Reopen the request in Discord.'})
|
||||
except (requests.RequestException, OSError, RuntimeError, TypeError, ValueError):
|
||||
self.json(503, {'error': 'Could not confirm delivery. Check the comma internet connection and your Discord thread.'})
|
||||
return
|
||||
if path == '/api/settings/flm-finding/accept':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -1929,6 +1984,43 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
return
|
||||
if path == '/api/sentry/notifications/photo-test':
|
||||
if (type(payload) is not dict or set(payload) != {'camera', 'id'} or payload['camera'] not in ('wide', 'cabin') or
|
||||
not isinstance(payload['id'], str) or not re.fullmatch(r'[0-9a-f]{12}', payload['id'])):
|
||||
self.json(400, {'error': 'Choose a phone and camera'})
|
||||
return
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
|
||||
def permitted():
|
||||
readable, _, _ = select.select([self.connection], [], [], 0)
|
||||
if readable and not self.connection.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT):
|
||||
return False
|
||||
return self.settings_session() == identity and parked()
|
||||
|
||||
try:
|
||||
photo = snapshots.capture(payload['camera'], permitted=permitted, parked=True)
|
||||
notification_owner.photo_test(payload['id'], payload['camera'], photo, permitted=permitted)
|
||||
except (SnapshotDenied, PermissionError):
|
||||
if self.require_session():
|
||||
self.json(409, {'error': 'Park the car before sending a photo test'})
|
||||
except SnapshotUnavailable:
|
||||
if self.require_session():
|
||||
self.json(503, {'error': 'No fresh camera frame. Try again shortly.'})
|
||||
except LookupError:
|
||||
self.json(404, {'error': 'Phone subscription not found'})
|
||||
except ValueError as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except (NotificationUnavailable, OSError):
|
||||
self.json(503, {'error': 'Sentry phone push is unavailable. Check Galaxy Sentry settings.'})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(200, {'queued': True})
|
||||
else:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/sentry/notifications':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
@@ -1942,11 +2034,32 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
if not parked():
|
||||
self.json(403, {'error': 'Park the car before simulating an event'})
|
||||
return
|
||||
if clock() - last_simulation[0] < 10:
|
||||
if simulation_busy.is_set() or clock() - last_simulation[0] < 10:
|
||||
self.json(429, {'error': 'Wait ten seconds before simulating another event'})
|
||||
return
|
||||
notification_owner.store.record('warning', time.monotonic_ns(), simulated=True,
|
||||
permitted=lambda: self.settings_session() == identity and parked())
|
||||
from openpilot.starpilot.sentry_mode.capture import record_motion_event
|
||||
direct_local = self.direct_local()
|
||||
|
||||
def permitted():
|
||||
return self.current_settings_session(identity[0], direct_local) == identity and parked()
|
||||
|
||||
def capture_simulation():
|
||||
try:
|
||||
record_motion_event(notification_owner.store, snapshots, 'warning', time.monotonic_ns(),
|
||||
permitted, simulated=True)
|
||||
except SnapshotDenied:
|
||||
pass
|
||||
except Exception:
|
||||
cloudlog.exception("Sentry simulation could not record the event")
|
||||
finally:
|
||||
simulation_busy.clear()
|
||||
|
||||
simulation_busy.set()
|
||||
try:
|
||||
threading.Thread(target=capture_simulation, name='sentry-simulation', daemon=True).start()
|
||||
except RuntimeError:
|
||||
simulation_busy.clear()
|
||||
raise NotificationUnavailable("Could not start Sentry simulation")
|
||||
last_simulation[0] = clock()
|
||||
result = notification_owner.snapshot()
|
||||
else:
|
||||
|
||||
@@ -137,7 +137,7 @@ const layout = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c',
|
||||
await page.evaluate(()=>location.hash='/tools')
|
||||
await page.getByRole('heading',{name:'Tools',exact:true}).waitFor()
|
||||
const sidebar=page.locator('.gx-nav-section').filter({has:page.locator('.gx-nav-section__title',{hasText:/^Tools$/})})
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Install'))
|
||||
assert.deepEqual(await sidebar.locator('.gx-nav-item span').allTextContents(), (await page.locator('.gx-menu-tile > span').allTextContents()).filter(name => name !== 'Galaxy Access & Connections'))
|
||||
assert.deepEqual(errors,[])
|
||||
console.log('Browser checks passed: VASM frame/default/reactive updates, PiP crop frame, widget registry, recordings and phone layout. Captures:',draws)
|
||||
await browser.close()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from "node:assert/strict"
|
||||
import { BluetoothFeed, BluetoothPage, validBluetoothStatus, validPairInput } from "../web/js/bluetooth.js"
|
||||
|
||||
@@ -111,3 +112,6 @@ assert.equal(validBluetoothStatus({ ...status, pairing: { address: "not-an-addre
|
||||
assert.equal(validBluetoothStatus({ ...status, adapterName: 5 }), false)
|
||||
assert.match(BluetoothPage.template, /Pair phone/)
|
||||
assert.match(BluetoothPage.template, /action\('accept_pair'\)/)
|
||||
|
||||
assert.equal(BluetoothPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(BluetoothPage.template.includes("<ConnectionLogs v-if=\"mode === 'local' && !unidenSettings\" panel"))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
"""Authenticated diagnostics over the same local and remote HTTP handler."""
|
||||
|
||||
import http.client
|
||||
@@ -57,12 +57,15 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
connection.close()
|
||||
|
||||
def test_real_http_routes_authentication_and_no_mutations(self):
|
||||
for path in ('/api/local-access', '/api/tmux/live', '/api/troubleshoot'):
|
||||
for path in ('/api/local-access', '/api/local-access/capture', '/api/tmux/live', '/api/troubleshoot'):
|
||||
self.assertEqual(self.request(path, remote=True)[0], 401)
|
||||
self.assertEqual(self.calls, [])
|
||||
status, _, self.cookie = self.request('/api/auth/session')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(self.request('/api/local-access')[1]['addresses'][0]['url'], 'http://192.168.4.2:8082/')
|
||||
status, capture, _ = self.request('/api/local-access/capture')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn('http://192.168.4.2:8082/', capture['text'])
|
||||
self.assertEqual(self.request('/api/tmux/live')[1]['text'], 'actual console')
|
||||
self.assertEqual(self.request('/api/troubleshoot')[1]['sections'], [])
|
||||
before = len(self.calls)
|
||||
@@ -70,6 +73,22 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.assertNotEqual(self.request('/api/tmux/live', method='POST', payload={})[0], 200)
|
||||
self.assertEqual(len(self.calls), before)
|
||||
|
||||
def test_support_code_captures_on_device_and_confirms_delivery(self):
|
||||
_, _, self.cookie = self.request('/api/auth/session')
|
||||
code = 'ab12' * 3
|
||||
path = '/api/companion/support-ticket'
|
||||
def post(action):
|
||||
return self.request(path, method='POST', payload={'code': code, 'action': action})
|
||||
ticket = Mock(status_code=200)
|
||||
ticket.json.return_value = {'title': 'Lost network', 'kind': 'connection'}
|
||||
receipt = Mock(status_code=200)
|
||||
receipt.json.return_value = {'sent': True}
|
||||
with patch('requests.post', side_effect=[ticket, ticket, receipt]) as relay:
|
||||
self.assertEqual(post('check')[1]['title'], 'Lost network')
|
||||
self.assertEqual(post('send')[:2], (200, {'sent': True}))
|
||||
self.assertTrue(relay.call_args.kwargs['json']['archive'].startswith('UEsD'))
|
||||
self.assertFalse(relay.call_args.kwargs['allow_redirects'])
|
||||
|
||||
def test_authenticated_forwarded_transport_uses_same_tools(self):
|
||||
status, _, self.cookie = self.request('/api/auth/login', method='POST', payload={'password': 'test-password-123'}, remote=True)
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRenderer, nextTick } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { GalaxyPage } from '../web/js/galaxy.js'
|
||||
import { RemoteAccess } from '../web/js/remote-access.js'
|
||||
@@ -36,10 +37,12 @@ const all = item => [item, ...item.children.flatMap(all)]
|
||||
const text = item => [item.text, ...item.children.map(text)].join(' ')
|
||||
const flush = async () => { await new Promise(resolve => setImmediate(resolve)); await nextTick() }
|
||||
const host = node('host')
|
||||
const { tools } = JSON.parse(readFileSync(new URL('../web/data/catalog.json', import.meta.url)))
|
||||
const galaxy = tools.find(tool => tool.path === '/galaxy')
|
||||
const visits = []
|
||||
const app = renderer.createApp({ ...GalaxyPage, components: { ...GalaxyPage.components,
|
||||
GalaxyHotspot: { template: '<div>Hotspot settings</div>' },
|
||||
InstallApp: { props: ['url'], template: '<div class="web-link">{{ url }}</div>' },
|
||||
} }, { mode: 'local', unauthorized() { unauthorized++ } })
|
||||
} }, { mode: 'local', tools: galaxy.children, go: path => visits.push(path), unauthorized() { unauthorized++ } })
|
||||
app.config.compilerOptions.decodeEntities = value => value.replaceAll('&', '&')
|
||||
const vm = app.mount(host)
|
||||
await flush()
|
||||
@@ -53,7 +56,14 @@ try {
|
||||
const stepList = nodes.find(item => item.type === 'ol' && item.props.class === 'gx-steps')
|
||||
assert.equal(stepList.children.filter(item => item.type === 'li' && item.props.class?.includes('gx-step')).length, 2)
|
||||
assert.equal(nodes.filter(item => item.props.class === 'gx-step__head').length, 2)
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|Connections|offline app version/)
|
||||
assert.match(text(host), /Galaxy Access & Connections/)
|
||||
assert.doesNotMatch(text(host), /MB today|Status:|offline app version/)
|
||||
assert.ok(tools.some(tool => tool.path === '/starport'), 'StarPort remains a standalone tool')
|
||||
const tiles = nodes.filter(item => item.props.class === 'gx-menu-tile')
|
||||
assert.deepEqual(tiles.map(item => item.children.find(child => child.type === 'span').text), ['Networks', 'Bluetooth'])
|
||||
for (const tile of tiles) tile.props.onClick()
|
||||
nodes.find(item => item.type === 'button' && item.text === 'Get help').props.onClick()
|
||||
assert.deepEqual(visits, ['/networks', '/bluetooth', '/logs/help'])
|
||||
assert.equal(requests.length, 1, 'A browser reads remote pairing status without polling Android internet-sharing status')
|
||||
assert.equal(requests[0][0], './api/galaxy/status')
|
||||
assert.equal(vm.url, link, 'Remote link reaches the web installer')
|
||||
|
||||
@@ -10,7 +10,7 @@ assert.ok(ids.every(id => recordArt(id).every(path => typeof path === "string" &
|
||||
assert.ok(recordArt("futureRecord").length)
|
||||
assert.ok(Home.template.includes('recordArt(record.id)'))
|
||||
assert.ok(Home.template.includes('aria-hidden="true"><svg'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Install</h2>'))
|
||||
assert.ok(GalaxyPage.template.includes('>Galaxy Access & Connections</h2>'))
|
||||
assert.ok(!GalaxyPage.template.includes('Galaxy & App Install'))
|
||||
assert.ok(!GalaxyPage.template.includes('Android users:'))
|
||||
assert.ok(!GalaxyPage.template.includes('Phone companion · Connections'))
|
||||
@@ -18,8 +18,8 @@ assert.ok(GalaxyPage.template.indexOf('<RemoteAccess') < GalaxyPage.template.ind
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
assert.ok(GalaxyPage.template.includes('<h3>Get the app</h3>'))
|
||||
assert.ok(GalaxyPage.template.includes('<InstallApp :url="url" />'))
|
||||
assert.ok(GalaxyPage.template.includes('href="#/networks"'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<InstallApp') < GalaxyPage.template.indexOf('#/networks'))
|
||||
assert.ok(GalaxyPage.template.includes('Get help'))
|
||||
assert.ok(GalaxyPage.template.indexOf('<MenuTile') < GalaxyPage.template.indexOf('<InstallApp'))
|
||||
assert.ok(!GalaxyPage.template.includes('PWA'))
|
||||
assert.ok(DriveStatePanel.template.includes('gx-card gx-force-drive'))
|
||||
const css = readFileSync(new URL('../web/css/galaxy.css', import.meta.url), 'utf8')
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
import { LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { ConnectionLogs, LocalAccess, LocalAccessFeed, validLocalAccess } from "../web/js/local-access.js"
|
||||
import { Home } from "../web/js/home.js"
|
||||
import { RemoteQR } from "../web/js/remote-access.js"
|
||||
import { GalaxyPage } from "../web/js/galaxy.js"
|
||||
const snapshot = { available: true, addresses: [{ interface: 'wlan0', label: 'Wi-Fi', url: 'http://192.168.20.5:8082/' }], reason: '' }
|
||||
assert.equal(validLocalAccess(snapshot), true)
|
||||
@@ -67,3 +68,57 @@ assert.equal(GalaxyPage.components.LocalAccess, undefined)
|
||||
assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
compile(GalaxyPage.template, { decodeEntities: value => value.replaceAll('&', '&') })
|
||||
console.log('Galaxy local access remains independent of app installation')
|
||||
|
||||
const capture = { onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
const originalFetch = globalThis.fetch
|
||||
try {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/local-access/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await capture.captureConnectionLogs()
|
||||
assert.equal(capture.capture.type, 'application/zip')
|
||||
assert.equal(capture.captureRequest, null)
|
||||
capture.resetCapture()
|
||||
assert.equal(capture.capture, null)
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
const thread = { ...ConnectionLogs.data(), ...ConnectionLogs.methods, supportCode: 'AB12 CD34-EF56' }
|
||||
try {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/companion/support-ticket')
|
||||
const { action, code } = JSON.parse(options.body)
|
||||
assert.equal(code, 'ab12cd34ef56')
|
||||
const body = action === 'check' ? { title: 'Lost network', kind: 'connection' } : { sent: true }
|
||||
return { ok: true, json: async () => body }
|
||||
}
|
||||
await thread.threadAction('check')
|
||||
assert.equal(thread.supportTicket.title, 'Lost network')
|
||||
assert.equal(thread.supportSent, false)
|
||||
await thread.threadAction('send')
|
||||
assert.equal(thread.supportSent, true)
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
assert.equal(LocalAccess.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(LocalAccess.template.includes("mode === 'local'"))
|
||||
compile(ConnectionLogs.template, { decodeEntities: value => value })
|
||||
assert.ok(ConnectionLogs.template.includes('Send to existing Discord thread'))
|
||||
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#submit-logs-through-discord'))
|
||||
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#report-a-problem-through-discord'))
|
||||
assert.match(ConnectionLogs.template, /<details[^>]*><summary><small>Manual ZIP download<\/small><\/summary>[\s\S]*Download ZIP<\/button>\s*<\/details>/)
|
||||
for (const endpoint of ['./api/galaxy/qr.svg', './api/galaxy/session/qr.svg']) {
|
||||
const qr = {endpoint, ...RemoteQR.data(), ...RemoteQR.methods}
|
||||
try {
|
||||
globalThis.fetch = async (path, options) => {
|
||||
assert.equal(path, endpoint)
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return new Response('<svg xmlns="http://www.w3.org/2000/svg"/>',{headers:{'Content-Type':'image/svg+xml'}})
|
||||
}
|
||||
await qr.load()
|
||||
assert.match(qr.image, /^blob:/)
|
||||
assert.equal(qr.failed, false)
|
||||
assert.equal((await originalFetch(qr.image)).headers.get('content-type'), 'image/svg+xml')
|
||||
RemoteQR.beforeUnmount.call(qr)
|
||||
await assert.rejects(originalFetch(qr.image))
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Pure bounded network/launcher readers; never imports native vehicle modules."""
|
||||
|
||||
import ast
|
||||
from base64 import b64decode
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import json
|
||||
@@ -8,7 +11,7 @@ import subprocess
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess
|
||||
from openpilot.starpilot.galaxy.local_access import LocalAccess, connection_capture
|
||||
from openpilot.starpilot.galaxy.tmux_live import TmuxLive, MAX_BYTES
|
||||
|
||||
|
||||
@@ -66,6 +69,56 @@ class TestNetworkDiagnostics(unittest.TestCase):
|
||||
for run in [lambda *_a, **_k: SimpleNamespace(stdout=b'x' * 65537), lambda *_a, **_k: (_ for _ in ()).throw(subprocess.TimeoutExpired('ip', 1))]:
|
||||
self.assertFalse(LocalAccess(run=run).snapshot()['available'])
|
||||
|
||||
def test_connection_capture_includes_only_known_advertiser_events(self):
|
||||
source, _ = self.addresses([interface()])
|
||||
commands = []
|
||||
|
||||
def run(args, **_kwargs):
|
||||
commands.append(args)
|
||||
if args[0] == 'systemctl':
|
||||
return SimpleNamespace(stdout=b'ActiveState=active\nSubState=running\nNRestarts=3\n')
|
||||
if args[0] == 'ip':
|
||||
state = [{'dev': 'wlan0', 'gateway': '192.168.50.1'}] if 'route' in args else [
|
||||
{'ifname': 'wlan0', 'operstate': 'UP', 'address': 'de:ad:be:ef:00:01',
|
||||
'addr_info': [{'local': '192.168.50.21', 'prefixlen': 24}, {'local': '8.8.8.8', 'prefixlen': 32}]}]
|
||||
return SimpleNamespace(stdout=json.dumps(state).encode())
|
||||
if args[0] == 'ss':
|
||||
return SimpleNamespace(stdout=b'LISTEN 0 20 0.0.0.0:8082 0.0.0.0:*')
|
||||
if 'galaxy-ble-fork.service' in args:
|
||||
return SimpleNamespace(stdout=b'{"MESSAGE":"Phone claimed pairing window"}')
|
||||
rows = [{'MESSAGE': 'Galaxy Wi-Fi discovery available on 1 local interface(s)'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: TimeoutExpired'},
|
||||
{'MESSAGE': 'Wi-Fi discovery unavailable: cookie=private'},
|
||||
{'MESSAGE': 'Tunnel password: private'}]
|
||||
return SimpleNamespace(stdout='\n'.join(map(json.dumps, rows)).encode())
|
||||
|
||||
capture = connection_capture(source.snapshot(), run=run)
|
||||
self.assertEqual(capture['schemaVersion'], 1)
|
||||
self.assertIn('http://192.168.50.21:8082/', capture['text'])
|
||||
self.assertIn('Bonjour advertiser: active', capture['text'])
|
||||
self.assertIn('Galaxy Wi-Fi discovery available on 1 local interface(s)', capture['text'])
|
||||
self.assertIn('Wi-Fi discovery unavailable: TimeoutExpired', capture['text'])
|
||||
self.assertNotIn('Tunnel password:', capture['text'])
|
||||
self.assertTrue(any('galaxy-lan-discovery.service' in args for args in commands))
|
||||
with ZipFile(BytesIO(b64decode(capture['zipBase64']))) as archive:
|
||||
self.assertEqual(archive.namelist(), ['connection-logs.txt'])
|
||||
report = archive.read('connection-logs.txt').decode()
|
||||
self.assertIn('192.168.50.21/24', report)
|
||||
self.assertIn('IPv4 default route interfaces: wlan0', report)
|
||||
self.assertIn('TCP port 8082 listening: all interfaces', report)
|
||||
self.assertIn('NRestarts=3', report)
|
||||
self.assertIn('Phone claimed pairing window', report)
|
||||
for private_value in ('de:ad:be:ef:00:01', '192.168.50.1', '8.8.8.8', 'cookie=private'):
|
||||
self.assertNotIn(private_value, report)
|
||||
|
||||
def missing(*_args, **_kwargs):
|
||||
raise FileNotFoundError()
|
||||
|
||||
partial = connection_capture(source.snapshot(), run=missing)['text']
|
||||
self.assertIn('Bonjour advertiser: unavailable', partial)
|
||||
self.assertIn('Advertiser journal unavailable', partial)
|
||||
self.assertIn('192.168.50.21', partial)
|
||||
|
||||
def test_console_uses_exact_readonly_launcher_pane_and_cache(self):
|
||||
source, calls = self.console(b'first\nsecond\n')
|
||||
result = source.snapshot()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs } from "../web/js/local-access.js"
|
||||
import assert from 'node:assert/strict'
|
||||
import { compile } from '../web/vendor/vue/vue.esm-browser.js'
|
||||
import { NetworksPage, validNetworks } from '../web/js/networks.js'
|
||||
@@ -66,3 +67,6 @@ const before = sent.length
|
||||
assert.equal(await vm.send({ action: 'cellular', value: false }), false)
|
||||
assert.equal(sent.length, before)
|
||||
vm.stop()
|
||||
|
||||
assert.equal(NetworksPage.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(NetworksPage.template.includes("<ConnectionLogs v-if=\"mode === 'local'\" panel"))
|
||||
|
||||
@@ -4,9 +4,11 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import SnapshotDenied
|
||||
from openpilot.starpilot.galaxy.server import make_remote_server, make_server
|
||||
from openpilot.starpilot.sentry_mode.notifications import NotificationOwner
|
||||
|
||||
@@ -19,16 +21,28 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
from openpilot.starpilot.sentry_mode.storage import EventStore
|
||||
owner.store = EventStore(root / 'events')
|
||||
parked = [True]
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0])
|
||||
photos = []
|
||||
jpeg = b'\xff\xd8\xff\xd9'
|
||||
class Camera:
|
||||
def capture_many(self, cameras, **options):
|
||||
return {camera: self.capture(camera, **options) for camera in cameras}
|
||||
def capture(self, camera, *, permitted, parked):
|
||||
if not parked or not permitted():
|
||||
raise SnapshotDenied
|
||||
photos.append(camera)
|
||||
return jpeg
|
||||
server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), notifications=owner, parked=lambda: parked[0],
|
||||
camera_snapshot=Camera())
|
||||
thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
thread.start()
|
||||
def request(payload=None, cookie=''):
|
||||
def request(payload=None, cookie='', path=None):
|
||||
connection = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3)
|
||||
headers = {'Cookie': cookie, 'Origin': f'http://127.0.0.1:{server.server_port}', 'Content-Type': 'application/json'}
|
||||
connection.request('POST' if payload is not None else 'GET', '/api/sentry/notifications' if payload is not None else '/api/auth/session',
|
||||
connection.request('POST' if payload is not None else 'GET', path or ('/api/sentry/notifications' if payload is not None else '/api/auth/session'),
|
||||
json.dumps(payload) if payload is not None else None, headers)
|
||||
reply = connection.getresponse()
|
||||
result = reply.status, json.loads(reply.read()), dict(reply.getheaders())
|
||||
raw = reply.read()
|
||||
result = reply.status, raw if reply.getheader('Content-Type') == 'image/jpeg' else json.loads(raw), dict(reply.getheaders())
|
||||
connection.close()
|
||||
return result
|
||||
try:
|
||||
@@ -38,11 +52,29 @@ class NotificationHTTPTests(unittest.TestCase):
|
||||
self.assertNotIn('test-token', json.dumps(result))
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': 'missing'}, cookie)[0], 404)
|
||||
self.assertEqual(request({'action': 'test', 'target': 'app', 'id': result['appSubscriptions'][0]['id']}, cookie)[0], 200)
|
||||
test_route = '/api/sentry/notifications/photo-test'
|
||||
test = {'camera': 'cabin', 'id': result['appSubscriptions'][0]['id']}
|
||||
self.assertEqual(request(test, path=test_route)[0], 401)
|
||||
parked[0] = False
|
||||
self.assertEqual(request(test, cookie, test_route)[0], 409)
|
||||
self.assertEqual(photos, [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 403)
|
||||
parked[0] = True
|
||||
self.assertEqual(request(test, cookie, test_route)[:2], (200, {'queued': True}))
|
||||
self.assertEqual(photos, ['cabin'])
|
||||
event_id = next(iter(owner.test_photos))
|
||||
image_path = f'/api/sentry/image/{event_id}/test'
|
||||
self.assertEqual(request(path=image_path)[0], 401)
|
||||
self.assertEqual(request(cookie=cookie, path=image_path)[:2], (200, jpeg))
|
||||
self.assertEqual(owner.store.snapshot()['events'], [])
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 200)
|
||||
self.assertTrue(owner.store.snapshot()['events'][0]['simulated'])
|
||||
deadline = time.monotonic() + 3
|
||||
while not owner.store.snapshot()['events'] and time.monotonic() < deadline:
|
||||
time.sleep(.01)
|
||||
event = owner.store.snapshot()['events'][0]
|
||||
self.assertTrue(event['simulated'])
|
||||
for camera in ('wide', 'cabin'):
|
||||
self.assertEqual(owner.store.image(event['eventId'], camera), jpeg)
|
||||
self.assertEqual(request({'action': 'simulate'}, cookie)[0], 429)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -1590,6 +1590,14 @@ border-top: 1px solid var(--outline-variant);
|
||||
@media (prefers-reduced-motion: reduce) { .gx-update-progress__fill--indeterminate { width: 100%; animation: none; opacity: .6; } }
|
||||
.gx-panel { padding: var(--panel-padding); min-width: 0; }
|
||||
.gx-card.gx-panel > .gx-section__header { margin: calc(-1 * var(--panel-padding)) calc(-1 * var(--panel-padding)) var(--sp-4); }
|
||||
.gx-connection-logs.gx-panel > .gx-section__header { margin-bottom: 0; }
|
||||
.gx-connection-logs .gx-log-form { display: grid; gap: var(--sp-3); margin-top: var(--sp-3); }
|
||||
.gx-log-form .gx-field { width: 100%; box-sizing: border-box; }
|
||||
.gx-log-form p { margin: 0; }
|
||||
.gx-log-form .gx-btn { justify-self: start; }
|
||||
@media (max-width: 600px) {
|
||||
.gx-connection-logs .gx-log-form .gx-btn, .gx-connection-logs details > summary.gx-btn { width: 100%; box-sizing: border-box; }
|
||||
}
|
||||
.gx-panel > :first-child { margin-top: 0; }
|
||||
.gx-panel > :last-child { margin-bottom: 0; }
|
||||
.gx-panel-footer { padding: 0 var(--panel-padding) var(--panel-padding); }
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
{
|
||||
"mode": "offline-preview",
|
||||
"tools": [
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Cameras & Monitoring",
|
||||
"path": "/cameras",
|
||||
@@ -39,11 +32,27 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Galaxy Access & Install",
|
||||
"name": "Galaxy Access & Connections",
|
||||
"path": "/galaxy",
|
||||
"icon": "bi-globe2",
|
||||
"description": "Pair for remote access, install Galaxy, or set up a Wi-Fi hotspot",
|
||||
"availability": "local-only"
|
||||
"description": "Remote access, app setup, networks, Bluetooth, and support",
|
||||
"availability": "local-only",
|
||||
"children": [
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Bluetooth",
|
||||
"path": "/bluetooth",
|
||||
"icon": "bi-bluetooth",
|
||||
"description": "Adapter power, saved devices and connections",
|
||||
"availability": "local-only"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Logs & Diagnostics",
|
||||
@@ -96,10 +105,10 @@
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "Help & Community",
|
||||
"name": "Get help",
|
||||
"path": "/logs/help",
|
||||
"icon": "bi-life-preserver",
|
||||
"description": "Guides and community help",
|
||||
"description": "Driving, phone connection, controllers, and StarPort support",
|
||||
"availability": "always"
|
||||
}
|
||||
]
|
||||
@@ -141,13 +150,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Networks",
|
||||
"path": "/networks",
|
||||
"icon": "bi-wifi",
|
||||
"description": "Preferred Wi-Fi, cellular data and the Galaxy hotspot",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "System Tools",
|
||||
"path": "/system",
|
||||
|
||||
@@ -154,7 +154,11 @@ createApp({
|
||||
state.drawerOpen = state.navPinned
|
||||
save(PIN_KEY, String(state.navPinned))
|
||||
},
|
||||
isActive(path) { return route.path === path || route.path.startsWith(path + "/") || (path === "/manage_models" && route.path === "/model_laboratory") },
|
||||
isActive(path) {
|
||||
if (path === "/galaxy" && ["/networks", "/bluetooth"].some(child =>
|
||||
route.path === child || route.path.startsWith(child + "/"))) return true
|
||||
return route.path === path || route.path.startsWith(path + "/") || (path === "/manage_models" && route.path === "/model_laboratory")
|
||||
},
|
||||
async signIn() {
|
||||
const password = authForm.password
|
||||
authForm.password = ""
|
||||
@@ -224,7 +228,7 @@ createApp({
|
||||
|
||||
</div>
|
||||
<div class="gx-nav-footer"><DevicePicker />
|
||||
<button type="button" class="gx-nav-item" :class="{active:isActive('/galaxy')}" @click="goFromMenu('/galaxy')"><i class="bi bi-globe"></i><span>Galaxy Access & Install</span></button>
|
||||
<button type="button" class="gx-nav-item" :class="{active:isActive('/galaxy')}" @click="goFromMenu('/galaxy')"><i class="bi bi-globe"></i><span>Galaxy Access & Connections</span></button>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="gx-content" :style="{'--route-direction': routeDirection}"><div class="gx-route-stage">
|
||||
@@ -254,11 +258,11 @@ createApp({
|
||||
<VasmPage v-else-if="route.path === '/cameras/vasm'" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" />
|
||||
<Tools v-else-if="route.path === '/tools'" :tools="visibleTools" :mode="state.monitorMode" />
|
||||
<SettingsPage @nested="ensureBackEntry" ref="activeSettings" v-else-if="route.path === '/developer/connect'" :mode="state.monitorMode" :unauthorized="sessionExpired" initial-section="developer" />
|
||||
<GalaxyPage v-else-if="route.path === '/galaxy'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<NetworksPage v-else-if="route.path === '/networks'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<GalaxyPage v-else-if="route.path === '/galaxy'" :mode="state.monitorMode" :tools="currentTool?.children || []" :unauthorized="sessionExpired" :go="go" />
|
||||
<NetworksPage v-else-if="route.path === '/networks'" :go="go" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<OnroadLayoutPage ref="activeLayout" v-else-if="['/theme_maker', '/theme_maker/starport', '/appearance'].includes(route.path)" :key="route.path" :projection="route.path === '/theme_maker/starport'" :initial-panel="route.path === '/appearance' ? 'display' : 'widgets'" :mode="state.monitorMode" :unauthorized="sessionExpired" @target="go($event === 'projection' ? '/theme_maker/starport' : '/theme_maker')" @close="routeBack" />
|
||||
<SettingsRecoveryPage v-else-if="route.path === '/settings/recovery'" :mode="state.monitorMode" :unauthorized="sessionExpired" />
|
||||
<Logs v-else-if="route.path === '/logs' || route.path.startsWith('/logs/') || ['/troubleshoot', '/manage_tmux'].includes(route.path)" :path="route.path === '/troubleshoot' ? '/logs/troubleshoot' : route.path === '/manage_tmux' ? '/logs/tmux' : route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :tools="currentTool?.children || []" />
|
||||
<Logs v-else-if="route.path === '/logs' || route.path.startsWith('/logs/') || ['/troubleshoot', '/manage_tmux'].includes(route.path)" :path="route.path === '/troubleshoot' ? '/logs/troubleshoot' : route.path === '/manage_tmux' ? '/logs/tmux' : route.path" :mode="state.monitorMode" :unauthorized="sessionExpired" :local-routes="state.monitorMode === 'local' && authState.localAccess" :tools="currentTool?.children || []" />
|
||||
<SoftwarePage v-else-if="route.path === '/system'" :mode="state.monitorMode" :unauthorized="sessionExpired" :restarting="baseline => updateRestart.start({ ...baseline, instance: deviceRestart.instance })"
|
||||
:preparing="baseline => updateRestart.prepare({ ...baseline, instance: deviceRestart.instance })" :cancel-preparation="() => updateRestart.cancelPreparation()" />
|
||||
<NavigationPage v-else-if="['/navigation', '/navigation/maps', '/navigation/setup'].includes(route.path)" :mode="state.monitorMode" :unauthorized="sessionExpired" :go="go" :tabs="currentTool?.children || []"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { UnidenPanel } from './uniden.js'
|
||||
import { GxState } from "./state.js"
|
||||
@@ -169,7 +170,7 @@ export class BluetoothFeed {
|
||||
}
|
||||
|
||||
export const BluetoothPage = {
|
||||
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog },
|
||||
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog, ConnectionLogs, ReportingGuide },
|
||||
props: { go: { type: Function, default: path => { location.hash = path } }, unidenSettings: Boolean, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
data: () => ({ status: null, busy: false, error: "", pairValue: "", now: Date.now(), claimAt: Date.now(), forgetting: null, adding: false, dismissedPairing: null }),
|
||||
mounted() {
|
||||
@@ -322,5 +323,7 @@ export const BluetoothPage = {
|
||||
<button class="gx-btn gx-btn--danger" :disabled="forgetting.state === 'working'" @click="confirmForget">{{ forgetting.state === 'working' ? 'Forgetting…' : forgetting.state === 'failed' ? 'Try again' : 'Forget' }}</button></div>
|
||||
</template>
|
||||
</GxDialog>
|
||||
</section>`,
|
||||
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel show-controller :on-unauthorized="unauthorized" @help="go('/logs/help')" />
|
||||
<ReportingGuide v-if="mode === 'local' && !unidenSettings" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
export const DrivingHelp = {
|
||||
props: {
|
||||
routeId: { type: String, default: "" },
|
||||
segment: { type: Number, default: null },
|
||||
connect: { type: String, default: "" },
|
||||
routesAvailable: Boolean,
|
||||
},
|
||||
emits: ["routes"],
|
||||
data: () => ({ copied: false }),
|
||||
computed: {
|
||||
routeDetails() {
|
||||
return this.routeId + (this.segment === null ? "" : " · Segment " + this.segment)
|
||||
},
|
||||
},
|
||||
watch: { routeDetails() { this.copied = false } },
|
||||
methods: {
|
||||
async copyDetails() {
|
||||
this.copied = false
|
||||
const details = this.routeDetails
|
||||
try {
|
||||
await navigator.clipboard.writeText(details)
|
||||
if (details === this.routeDetails) this.copied = true
|
||||
} catch {
|
||||
// Local Galaxy commonly runs on HTTP, where the Clipboard API is unavailable.
|
||||
this.$refs.details?.select()
|
||||
}
|
||||
},
|
||||
},
|
||||
template: `<div class="gx-stack">
|
||||
<p class="gx-note">Find the drive, then share the route link and approximate timestamp or segment. Describe what the car did and what you expected.</p>
|
||||
<div v-if="routeId" class="gx-actions">
|
||||
<input ref="details" class="gx-field" aria-label="Route and segment for support" :value="routeDetails" readonly @focus="$event.target.select()">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="copyDetails">{{ copied ? 'Copied' : 'Copy route details' }}</button>
|
||||
</div>
|
||||
<div class="gx-actions">
|
||||
<button v-if="!routeId && routesAvailable" type="button" class="gx-btn gx-btn--tonal" @click="$emit('routes')">Open Galaxy Routes</button>
|
||||
<a class="gx-btn gx-btn--tonal" :href="connect || 'https://connect.comma.ai/'" target="_blank" rel="noopener noreferrer">{{ connect ? 'Open this route online' : 'Open comma connect' }}</a>
|
||||
<a class="gx-btn gx-btn--tonal" href="https://discord.com/channels/1387432184121393333/1506463404863389806" target="_blank" rel="noopener noreferrer">Driving support on Discord</a>
|
||||
</div>
|
||||
<p v-if="!routeId && !routesAvailable" class="gx-note">Connect directly to your comma to browse saved Galaxy routes.</p>
|
||||
</div>`,
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MenuTile } from './menu-tile.js'
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { AppStoreLinks } from './app-downloads.js'
|
||||
import { InstallApp } from './install-app.js'
|
||||
@@ -6,12 +7,25 @@ import { CompanionUpdates } from './companion-updates.js'
|
||||
|
||||
export const GalaxyPage = {
|
||||
name: 'GalaxyPage',
|
||||
components: { WikiHelp, AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates },
|
||||
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
components: { WikiHelp, AppStoreLinks, InstallApp, RemoteAccess, CompanionUpdates, MenuTile },
|
||||
props: {
|
||||
mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
|
||||
tools: { type: Array, default: () => [] }, go: { type: Function, default: path => { location.hash = path } },
|
||||
},
|
||||
data: () => ({ url: '' }),
|
||||
template: `<div class="gx-settings gx-tunnel">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Galaxy Access & Install</h2>
|
||||
<p>Set up your link, then choose how to open Galaxy.</p></div><WikiHelp /></header>
|
||||
<header class="gx-settings__header gx-page-header">
|
||||
<div><h2>Galaxy Access & Connections</h2></div>
|
||||
<div class="gx-actions">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/help')">Get help</button>
|
||||
<WikiHelp />
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="tools.length" class="gx-grid">
|
||||
<MenuTile v-for="tool in tools" :key="tool.path" :icon="tool.icon" :title="tool.name"
|
||||
:description="tool.description" :disabled="mode !== 'local'" :availability="mode !== 'local' ? 'Connect to your comma' : ''"
|
||||
@select="go(tool.path)" />
|
||||
</div>
|
||||
<ol class="gx-steps">
|
||||
<RemoteAccess title="Set up remote access" :mode="mode" :unauthorized="unauthorized" @link="url = $event" />
|
||||
<li class="gx-card gx-step" aria-label="Get the app">
|
||||
@@ -24,8 +38,5 @@ export const GalaxyPage = {
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<section class="gx-card gx-panel gx-stack"><div class="gx-section__header"><i class="bi bi-wifi" aria-hidden="true"></i><span class="gx-section__title">Galaxy Wi-Fi Hotspot</span></div>
|
||||
<p>The hotspot, preferred Wi-Fi networks and cellular data are on the Networks page.</p>
|
||||
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" href="#/networks">Open Networks</a></div></section>
|
||||
</div>`,
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ export const Home = {
|
||||
template: `
|
||||
<div class="gx-view gx-home">
|
||||
<div class="gx-home__hero gx-page-header">
|
||||
<div><h1>Dashboard</h1><p class="gx-note">Your saved drives and current device</p></div><WikiHelp />
|
||||
<div><h1>Dashboard</h1><p class="gx-note">Your saved drives and current device</p></div><div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/help')">Get help</button><WikiHelp /></div>
|
||||
</div>
|
||||
<GxState v-if="mode !== 'local'">Dashboard information is available on your device.</GxState>
|
||||
<template v-else>
|
||||
|
||||
@@ -13,7 +13,7 @@ export function isAndroidDevice(agent = typeof navigator === 'undefined' ? '' :
|
||||
}
|
||||
|
||||
export function installHelp({ secure = window.isSecureContext, agent = navigator.userAgent } = {}) {
|
||||
if (!secure) return 'Bookmark this local address for hotspot or Wi-Fi access without Internet. To install Galaxy as a web app (PWA), open your device-specific https://galaxy.firestar.link link from Galaxy Access & Install; this remote link needs Internet.'
|
||||
if (!secure) return 'Bookmark this local address for hotspot or Wi-Fi access without Internet. To install Galaxy as a web app (PWA), open your device-specific https://galaxy.firestar.link link from Galaxy Access & Connections; this remote link needs Internet.'
|
||||
if (/iPhone|iPad|iPod/.test(agent)) return 'Open Galaxy in Safari, tap Share, then Add to Home Screen. Turn on Open as Web App if shown.'
|
||||
return 'This browser cannot install Galaxy automatically. Open the browser menu and choose Install app or Add to Home Screen. On a Mac in Safari, choose File → Add to Dock.'
|
||||
}
|
||||
|
||||
@@ -49,8 +49,122 @@ export class LocalAccessFeed {
|
||||
}
|
||||
}
|
||||
|
||||
export const ReportingGuide = {
|
||||
template: `<p class="gx-note">Reporting a new companion app issue? Read the instructions for
|
||||
<a href="https://wiki.firestar.link/usage/companion-apps/ios/#submit-logs-through-discord" target="_blank" rel="noopener noreferrer">iPhone</a> or
|
||||
<a href="https://wiki.firestar.link/usage/companion-apps/android/#report-a-problem-through-discord" target="_blank" rel="noopener noreferrer">Android</a>.</p>`,
|
||||
}
|
||||
|
||||
export const ConnectionLogs = {
|
||||
components: { GxNotice, ReportingGuide },
|
||||
props: { ticket: String, panel: Boolean, controller: Boolean, showController: Boolean, onUnauthorized: { type: Function, default: () => {} } },
|
||||
emits: ["help"],
|
||||
data: () => ({ supportCode: "", supportTicket: null, supportBusy: false, supportSent: false, capture: null, captureError: "", captureRequest: null }),
|
||||
beforeUnmount() { this.resetCapture() },
|
||||
methods: {
|
||||
resetCapture() {
|
||||
this.captureRequest?.abort()
|
||||
this.captureRequest = null
|
||||
this.capture = null
|
||||
this.captureError = ""
|
||||
},
|
||||
async threadAction(action) {
|
||||
if (this.supportBusy) return
|
||||
this.supportBusy = true
|
||||
this.captureError = ""
|
||||
try {
|
||||
const result = await requestJson("./api/companion/support-ticket", { timeout: 90000, request: {
|
||||
method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({action, code: this.supportCode.replace(/[\s-]/g, "").toLowerCase()})
|
||||
}})
|
||||
if (action === "check") this.supportTicket = result
|
||||
else this.supportSent = result.sent === true
|
||||
} catch (error) {
|
||||
if (error.status === 401) this.onUnauthorized()
|
||||
else this.captureError = error.message
|
||||
} finally { this.supportBusy = false }
|
||||
},
|
||||
async captureConnectionLogs() {
|
||||
if (this.captureRequest) return
|
||||
const request = new AbortController()
|
||||
this.captureRequest = request
|
||||
this.capture = null
|
||||
this.captureError = ""
|
||||
try {
|
||||
const endpoint = this.controller ? "./api/controllers/log/capture" : "./api/local-access/capture"
|
||||
const data = await requestJson(endpoint, { request: { signal: request.signal } })
|
||||
if (this.captureRequest !== request) return
|
||||
if (data?.schemaVersion !== 1 || typeof data.zipBase64 !== "string" || data.zipBase64.length > 131072)
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
const bytes = Uint8Array.from(atob(data.zipBase64), character => character.charCodeAt(0))
|
||||
if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4)
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
this.capture = new Blob([bytes], { type: "application/zip" })
|
||||
if (this.ticket && /^[a-f0-9]{64}$/.test(this.ticket)) {
|
||||
const form = document.createElement("form")
|
||||
form.method = "post"
|
||||
form.action = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/" + this.ticket
|
||||
const input = document.createElement("input")
|
||||
input.type = "hidden"
|
||||
input.name = "archive"
|
||||
input.value = data.zipBase64
|
||||
form.appendChild(input)
|
||||
document.body.appendChild(form)
|
||||
form.submit()
|
||||
form.remove()
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.captureRequest !== request) return
|
||||
if (error.status === 401 || ["setup_required", "access_unavailable"].includes(error.code)) this.onUnauthorized()
|
||||
else this.captureError = connectionError(error)
|
||||
} finally {
|
||||
if (this.captureRequest === request) this.captureRequest = null
|
||||
}
|
||||
},
|
||||
downloadConnectionLogs() {
|
||||
if (!this.capture) return
|
||||
const url = URL.createObjectURL(this.capture)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = this.controller ? "starpilot-controller-logs.zip" : "starpilot-connection-logs.zip"
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
},
|
||||
},
|
||||
template: `<div class="gx-stack gx-connection-logs" :class="{ 'gx-card gx-panel': panel }">
|
||||
<div v-if="panel" class="gx-section__header"><i class="bi bi-file-earmark-text" aria-hidden="true"></i><span class="gx-section__title">Connection logs</span>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="$emit('help')">Get help</button>
|
||||
</div>
|
||||
<div v-if="panel" class="gx-actions"><a class="gx-btn gx-btn--tonal" href="https://wiki.firestar.link/usage/companion-apps/#pair-your-phone" target="_blank" rel="noopener noreferrer">App connection help</a></div>
|
||||
<details v-if="!ticket"><summary class="gx-btn">Send to existing Discord thread</summary>
|
||||
<p v-if="supportSent" role="status">Support received the logs. Your Discord thread has the receipt.</p>
|
||||
<form v-else class="gx-log-form" @submit.prevent="threadAction(supportTicket ? 'send' : 'check')">
|
||||
<label class="gx-field-group">Discord request code<input class="gx-field" v-model="supportCode" :disabled="supportBusy" @input="supportTicket = null; captureError = ''" maxlength="24" autocomplete="off" spellcheck="false"></label>
|
||||
<button v-if="!supportTicket" class="gx-btn" type="submit" :disabled="supportBusy || !supportCode.trim()">{{ supportBusy ? 'Finding report…' : 'Find report' }}</button>
|
||||
<template v-else><p>{{ supportTicket.title }}</p><p>Only support staff receive the {{ supportTicket.kind }} logs.</p>
|
||||
<button class="gx-btn" type="submit" :disabled="supportBusy">{{ supportBusy ? 'Sending…' : 'Capture and send' }}</button>
|
||||
</template>
|
||||
</form>
|
||||
</details>
|
||||
<details v-if="!ticket"><summary><small>Manual ZIP download</small></summary>
|
||||
<p v-if="showController" class="gx-note">For controller ZIPs, open Get help and choose Bluetooth Controller Support.</p>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture logs' }}</button>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!capture" @click="downloadConnectionLogs">Download ZIP</button>
|
||||
</details>
|
||||
<div v-else class="gx-actions">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture and send' }}</button>
|
||||
|
||||
</div>
|
||||
<GxNotice v-if="captureError" tone="danger">{{ captureError }}</GxNotice>
|
||||
<p v-if="capture && !ticket" class="gx-note" role="status">Capture ready. Download it to share with support.</p>
|
||||
<ReportingGuide v-if="!panel && !ticket" />
|
||||
</div>`,
|
||||
}
|
||||
|
||||
export const LocalAccess = {
|
||||
components: { GxNotice },
|
||||
components: { GxNotice, ConnectionLogs },
|
||||
props: { mode: { type: String, required: true }, onUnauthorized: { type: Function, default: () => {} } },
|
||||
setup(props) {
|
||||
const state = reactive({ loading: false, data: null, error: "" })
|
||||
@@ -69,5 +183,6 @@ export const LocalAccess = {
|
||||
<p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p>
|
||||
</template>
|
||||
<p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :on-unauthorized="onUnauthorized" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { DrivingHelp } from "./driving-help.js"
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
@@ -12,10 +14,10 @@ import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
|
||||
|
||||
export const Logs = {
|
||||
name: "Logs",
|
||||
components: { WikiHelp, GxState, GxNotice, BluetoothNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile },
|
||||
components: { WikiHelp, GxState, GxNotice, BluetoothNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile, DrivingHelp, ConnectionLogs },
|
||||
props: {
|
||||
path: { type: String, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
|
||||
tools: { type: Array, required: true }
|
||||
tools: { type: Array, required: true }, localRoutes: Boolean
|
||||
},
|
||||
data: () => ({
|
||||
crashes: { reports: [], scanIncomplete: false, listLimited: false, status: "idle", error: "", selected: null, preview: null, previewStatus: "idle", deleting: false, storageBytes: 0, reportCount: 0 }, search: "",
|
||||
@@ -23,6 +25,10 @@ export const Logs = {
|
||||
logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT
|
||||
}),
|
||||
computed: {
|
||||
freshRequest() {
|
||||
const match = /^\/logs\/help\/fresh\/(connection|controller)\/([a-f0-9]{64})$/.exec(this.path)
|
||||
return match && { controller: match[1] === "controller", token: match[2] }
|
||||
},
|
||||
visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) },
|
||||
},
|
||||
created() {
|
||||
@@ -70,11 +76,40 @@ export const Logs = {
|
||||
:availability="mode !== 'local' && tool.availability === 'local-only' ? 'Unavailable in preview' : ''"
|
||||
:disabled="mode !== 'local' && tool.availability === 'local-only'" @select="go(tool.path)" />
|
||||
</div>
|
||||
<section v-else-if="freshRequest" class="gx-settings">
|
||||
<header class="gx-settings__header"><h2>Requested {{ freshRequest.controller ? 'controller' : 'connection' }} logs</h2></header>
|
||||
<p class="gx-note">Capture fresh diagnostics for your support report. Only support staff receive the log file.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :key="freshRequest.token" :ticket="freshRequest.token" :controller="freshRequest.controller" :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture these logs.</p>
|
||||
</section>
|
||||
<section v-else-if="path === '/logs/help'" class="gx-settings">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Help & Community</h2><p>Guides and help from the community.</p></div><WikiHelp path="/logs/help" /></header>
|
||||
<section class="gx-card"><div class="gx-section__header"><i class="bi bi-discord" aria-hidden="true"></i><span class="gx-section__title">Discord</span></div>
|
||||
<div class="gx-panel"><p class="gx-note">Ask the community for help, share what you have tried, and follow StarPilot announcements.</p>
|
||||
<a class="gx-btn gx-btn--tonal" href="https://firestar.link/discord" target="_blank" rel="noopener noreferrer">Join Discord</a></div></section>
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Get help</h2><p>Choose what went wrong.</p></div><WikiHelp path="/logs/help" /></header>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Driving behavior or a specific drive">
|
||||
<div class="gx-section__header"><i class="bi bi-car-front" aria-hidden="true"></i><h3 class="gx-section__title">Driving behavior or a specific drive</h3></div>
|
||||
<DrivingHelp :routes-available="localRoutes" @routes="go('/recordings')" />
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Mobile App Support">
|
||||
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">Mobile App Support</h3></div>
|
||||
<p class="gx-note">For Wi-Fi, Bluetooth pairing, or Galaxy Tunnel issues. Send connection logs privately with your Discord account. If you use StarPilot on iPhone, you can also report from Logs & support.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture its connection logs.</p>
|
||||
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Bluetooth Controller Support">
|
||||
<div class="gx-section__header"><i class="bi bi-controller" aria-hidden="true"></i><h3 class="gx-section__title">Bluetooth Controller Support</h3></div>
|
||||
<p class="gx-note">Connect and wake your USB or Bluetooth controller before capturing its input report. Include the controller model and what went wrong when you send it.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" controller :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture a controller log.</p>
|
||||
<div class="gx-actions">
|
||||
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/bluetooth/controllers')">Open Controllers</button>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="StarPort / Android Auto Support">
|
||||
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">StarPort / Android Auto Support</h3></div>
|
||||
<p class="gx-note">Open StarPort Logs to download your session bundle or send it to the developer.</p>
|
||||
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/starport')">Open StarPort Logs</button>
|
||||
</section>
|
||||
</section>
|
||||
<TroubleshootPage v-else-if="path === '/logs/troubleshoot'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
|
||||
<TmuxPage v-else-if="path === '/logs/tmux'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { requestJson } from "./startup.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
@@ -28,8 +29,8 @@ export const choiceRow = (label, value, choices, reason = '') => ({ label, value
|
||||
|
||||
export const NetworksPage = {
|
||||
name: "NetworksPage",
|
||||
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog },
|
||||
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog, ConnectionLogs, ReportingGuide },
|
||||
props: { go: { type: Function, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, adding: false, joiningSsid: '', joinPassword: '',
|
||||
hiddenOpen: false, hiddenSsid: '', showJoinPassword: false, forgetUuid: null, timer: null, controller: null, generation: 0, active: false }),
|
||||
computed: {
|
||||
@@ -261,5 +262,7 @@ export const NetworksPage = {
|
||||
</template>
|
||||
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
|
||||
<GalaxyHotspot v-if="mode === 'local'" :mode="mode" :unauthorized="unauthorized" />
|
||||
<ConnectionLogs v-if="mode === 'local'" panel :on-unauthorized="unauthorized" @help="go('/logs/help')" />
|
||||
<ReportingGuide v-if="mode === 'local'" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -3,9 +3,33 @@ import { GxNotice } from './notice.js'
|
||||
import { requestJson } from './startup.js'
|
||||
import { BluetoothNotice, bluetoothConnection } from './bluetooth-notice.js'
|
||||
|
||||
export const RemoteQR = {
|
||||
props: { endpoint: {type: String, required: true}, alt: {type: String, required: true} },
|
||||
data: () => ({image: '', failed: false, request: null}),
|
||||
mounted() { this.load() },
|
||||
beforeUnmount() { this.request?.abort(); if (this.image) URL.revokeObjectURL(this.image) },
|
||||
methods: {
|
||||
async load() {
|
||||
this.request?.abort()
|
||||
const request = new AbortController()
|
||||
this.request = request
|
||||
this.failed = false
|
||||
try {
|
||||
const response = await fetch(this.endpoint, {credentials: 'same-origin', cache: 'no-store', signal: request.signal})
|
||||
if (!response.ok || response.headers.get('content-type')?.split(';')[0] !== 'image/svg+xml') throw Error()
|
||||
const blob = await response.blob()
|
||||
if (request.signal.aborted) return
|
||||
if (this.image) URL.revokeObjectURL(this.image)
|
||||
this.image = URL.createObjectURL(blob)
|
||||
} catch { if (!request.signal.aborted) this.failed = true }
|
||||
},
|
||||
},
|
||||
template: '<div><button v-if="failed" class="gx-btn" @click="load">Retry QR code</button><img v-else-if="image" :src="image" :alt="alt" class="gx-tunnel__qr" @error="failed = true" /></div>',
|
||||
}
|
||||
|
||||
export const RemoteAccess = {
|
||||
name: 'RemoteAccess',
|
||||
components: { GxState, GxNotice, BluetoothNotice },
|
||||
components: { GxState, GxNotice, BluetoothNotice, RemoteQR },
|
||||
props: { title: { type: String, default: 'Remote access' }, step: { type: Number, default: 1 }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
emits: ['link'],
|
||||
data: () => ({ loading: true, paired: false, url: '', tunnelClientAvailable: false, legacyPassword: false,
|
||||
@@ -98,12 +122,12 @@ export const RemoteAccess = {
|
||||
<template v-if="paired">
|
||||
<GxNotice v-if="!tunnelClientAvailable" tone="warn">Remote access is not ready on this comma yet.</GxNotice>
|
||||
<BluetoothNotice v-if="bluetooth" feature="Galaxy QR code">Your Galaxy link remains available below.</BluetoothNotice>
|
||||
<img v-else src="./api/galaxy/qr.svg" alt="QR code for your Galaxy link" class="gx-tunnel__qr" />
|
||||
<RemoteQR v-else :key="url" endpoint="./api/galaxy/qr.svg" alt="QR code for your Galaxy link" />
|
||||
<p><a :href="url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">Open your Galaxy link</a></p>
|
||||
<section class="gx-card gx-panel gx-stack"><h3>App key</h3><p>Use this key to add remote access in the phone app. Keep it private.</p>
|
||||
<div v-if="!keyVisible" class="gx-actions"><button class="gx-btn" @click="showAppKey">Show</button></div>
|
||||
<template v-else><code class="gx-wrap">{{ appKey }}</code><div class="gx-actions"><button class="gx-btn" @click="copyAppKey">Copy</button></div>
|
||||
<img src="./api/galaxy/session/qr.svg" class="gx-tunnel__qr" alt="Add remote access to Galaxy" /></template>
|
||||
<RemoteQR endpoint="./api/galaxy/session/qr.svg" alt="Add remote access to Galaxy" /></template>
|
||||
</section>
|
||||
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--danger" @click="unpair">{{ busy ? 'Disconnecting…' : 'Turn off remote access' }}</button></div>
|
||||
</template>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DrivingHelp } from "./driving-help.js"
|
||||
import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { GxIconButton } from "./icon-button.js"
|
||||
@@ -11,7 +12,7 @@ import { LOCAL, VIDEOS, hasVideo, availableFiles, validRouteDetail, routeDate, c
|
||||
logUrl, logArchiveUrl, connectRouteUrl, formatBytes, detailMetric, segmentSummaryUrl, validSegmentSummary } from "./recording-data.js"
|
||||
|
||||
export const RouteWorkspace = {
|
||||
components: { GxState, GxNotice, GxIconButton, GxDialog, GalaxySelect, RecordingActions, CameraViewer, ReplayViewer },
|
||||
components: { GxState, GxNotice, GxIconButton, GxDialog, GalaxySelect, RecordingActions, CameraViewer, ReplayViewer, DrivingHelp },
|
||||
props: { routeId: { type: String, required: true }, summary: { type: Object, default: null },
|
||||
initialMode: { type: String, default: "footage" }, exports: { type: Object, required: true }, unauthorized: { type: Function, required: true } },
|
||||
emits: ["back", "changed"],
|
||||
@@ -198,6 +199,10 @@ export const RouteWorkspace = {
|
||||
<GxState v-if="status === 'loading'" loading>Reading saved route…</GxState>
|
||||
<GxNotice v-if="error" tone="danger">{{ error }}<template #actions v-if="status === 'unavailable'"><button class="gx-btn gx-btn--tonal" @click="load">Retry route</button></template></GxNotice>
|
||||
<template v-if="status === 'ready' && route">
|
||||
<details class="gx-card gx-panel">
|
||||
<summary>Get help with this drive</summary>
|
||||
<DrivingHelp :route-id="routeId" :segment="segment?.number ?? null" :connect="connect || ''" />
|
||||
</details>
|
||||
<GxNotice v-if="!route.inventoryComplete" tone="warn">{{ route.reason || 'Some route files could not be inspected.' }} Route downloads require a complete inventory.</GxNotice>
|
||||
<div class="gx-route-workspace__body">
|
||||
<section class="gx-card gx-route-workspace__viewer" aria-label="Route viewer">
|
||||
|
||||
@@ -6,6 +6,7 @@ const start = () => {
|
||||
const hash = location.hash.slice(1) || "/"
|
||||
let path
|
||||
try { path = decodeURIComponent(hash) } catch { path = hash }
|
||||
if (path === "/connections") return "/galaxy"
|
||||
return path === "/vehicle" ? "/settings/vehicle" : path
|
||||
}
|
||||
route.path = start()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Capture the camera evidence for a parked motion event."""
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import SnapshotDenied, SnapshotUnavailable
|
||||
|
||||
|
||||
def record_motion_event(store, camera, kind, stamp, permitted, *, simulated=False):
|
||||
try:
|
||||
results = camera.capture_many(("wide", "cabin"), permitted=permitted, parked=True)
|
||||
except SnapshotDenied:
|
||||
raise
|
||||
except SnapshotUnavailable:
|
||||
results = {}
|
||||
images = {name: body for name, body in results.items() if isinstance(body, bytes)}
|
||||
return store.record(kind, stamp, permitted=permitted, images=images, simulated=simulated)
|
||||
@@ -31,6 +31,8 @@ APP_IDS = ('com.starpilot.galaxy', 'link.firestar.companion', 'link.galaxy.bluet
|
||||
MAX_STATE_BYTES = 1024 * 1024
|
||||
MAX_JOBS = 512
|
||||
MAX_AGE = 86400
|
||||
TEST_PHOTO_AGE = 900
|
||||
MAX_TEST_PHOTOS = 4
|
||||
MAX_ATTEMPTS = 4
|
||||
RETRY_SECONDS = (30, 120, 600, 600)
|
||||
ID = re.compile(r'[0-9a-f]{32}\Z')
|
||||
@@ -83,6 +85,7 @@ class NotificationOwner:
|
||||
self.stop = threading.Event()
|
||||
self.thread = None
|
||||
self.state = fresh_state()
|
||||
self.test_photos: dict[str, tuple[float, bytes]] = {}
|
||||
self.available = True
|
||||
self.lock_fd = None
|
||||
self.saved_bytes = None
|
||||
@@ -430,6 +433,47 @@ class NotificationOwner:
|
||||
self._save()
|
||||
return self.snapshot()
|
||||
|
||||
def photo_test(self, target_id: str, camera: str, jpeg: bytes, *, permitted) -> None:
|
||||
if not isinstance(target_id, str) or re.fullmatch(r'[0-9a-f]{12}', target_id) is None or camera not in ('wide', 'cabin'):
|
||||
raise ValueError('Choose a phone and camera')
|
||||
if not isinstance(jpeg, bytes) or not 4 <= len(jpeg) <= 1_000_000 or not jpeg.startswith(b'\xff\xd8\xff'):
|
||||
raise NotificationUnavailable('No fresh camera image')
|
||||
with self.lock:
|
||||
if not self.available:
|
||||
raise NotificationUnavailable('Notification storage is unavailable')
|
||||
if not permitted():
|
||||
raise PermissionError('A current parked Galaxy session is required')
|
||||
if not any(sub['id'] == target_id for sub in self.state['appSubscriptions']):
|
||||
raise LookupError('Phone subscription not found')
|
||||
if not self.state['channels']['appPush']['enabled'] or len(self.state['jobs']) >= MAX_JOBS:
|
||||
raise NotificationUnavailable('Phone push is unavailable or its queue is full')
|
||||
now = self.clock()
|
||||
if sum(job['kind'] == 'test' and job['created'] > now - 60 for job in self.state['jobs'].values()) >= 4:
|
||||
raise ValueError('Wait a minute before sending more tests')
|
||||
event_id = uuid.uuid4().hex
|
||||
self._enqueue({'eventId': event_id, 'kind': 'test', 'wallTimeNs': int(now * 1e9)},
|
||||
only='appPush', target_id=target_id)
|
||||
try:
|
||||
if not permitted():
|
||||
raise PermissionError('Galaxy session or parked state changed')
|
||||
self._save()
|
||||
except (PermissionError, NotificationUnavailable, OSError):
|
||||
self.state['jobs'] = {key: job for key, job in self.state['jobs'].items() if job['eventId'] != event_id}
|
||||
raise
|
||||
self._expire_test_photos(now)
|
||||
if len(self.test_photos) >= MAX_TEST_PHOTOS:
|
||||
del self.test_photos[next(iter(self.test_photos))]
|
||||
self.test_photos[event_id] = (now + TEST_PHOTO_AGE, jpeg)
|
||||
|
||||
def _expire_test_photos(self, now):
|
||||
self.test_photos = {event: photo for event, photo in self.test_photos.items() if photo[0] > now}
|
||||
|
||||
def test_image(self, event_id: str) -> bytes | None:
|
||||
with self.lock:
|
||||
self._expire_test_photos(self.clock())
|
||||
photo = self.test_photos.get(event_id)
|
||||
return photo[1] if photo else None
|
||||
|
||||
def _enqueue(self, event: dict, *, only: str | None = None, target_id: str | None = None) -> None:
|
||||
if event['kind'] == 'selfie':
|
||||
return
|
||||
@@ -473,6 +517,9 @@ class NotificationOwner:
|
||||
return remove()
|
||||
|
||||
def tick(self) -> None:
|
||||
with self.lock:
|
||||
if self.test_photos:
|
||||
self._expire_test_photos(self.clock())
|
||||
with self.lock:
|
||||
if not self.available:
|
||||
return
|
||||
|
||||
@@ -241,17 +241,11 @@ def main() -> None:
|
||||
messages = messaging.SubMaster(["accelerometer", "deviceState", "pandaStates", "peripheralState"])
|
||||
store = EventStore()
|
||||
from openpilot.starpilot.galaxy.camera_request import request as prewarm_camera
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import CameraSnapshot, SnapshotDenied, SnapshotUnavailable
|
||||
from openpilot.starpilot.galaxy.camera_snapshot import CameraSnapshot
|
||||
from openpilot.starpilot.sentry_mode.capture import record_motion_event
|
||||
camera = CameraSnapshot()
|
||||
def record(kind, stamp, permitted):
|
||||
try:
|
||||
results = camera.capture_many(("wide", "cabin"), permitted=permitted, parked=True)
|
||||
except SnapshotDenied:
|
||||
raise
|
||||
except SnapshotUnavailable:
|
||||
results = {}
|
||||
images = {name: body for name, body in results.items() if isinstance(body, bytes)}
|
||||
return store.record(kind, stamp, permitted=permitted, images=images)
|
||||
return record_motion_event(store, camera, kind, stamp, permitted)
|
||||
def battery(voltage, cutoff):
|
||||
if recent_battery_warning(store.snapshot()["events"], time.time_ns()):
|
||||
return
|
||||
|
||||
@@ -279,6 +279,7 @@ class EventStore:
|
||||
if not _valid(value, event_id):
|
||||
raise ValueError("Invalid event metadata")
|
||||
if value.get('simulated') and time.time_ns() - value['wallTimeNs'] > 600_000_000_000:
|
||||
remove_entry(directory, event_id, [16])
|
||||
os.unlink(entry.name, dir_fd=directory)
|
||||
continue
|
||||
result["events"].append(value)
|
||||
|
||||
@@ -148,9 +148,10 @@ def test_simulated_events_expire_without_removing_real_events(tmp_path, monkeypa
|
||||
store = EventStore(tmp_path / 'events')
|
||||
clock = [1000000000000]
|
||||
monkeypatch.setattr(time, 'time_ns', lambda: clock[0])
|
||||
fake = store.record('warning', 1, permitted=lambda: True, simulated=True)
|
||||
fake = store.record('warning', 1, permitted=lambda: True, simulated=True, images={'wide': b'\xff\xd8\xff\xd9'})
|
||||
real = store.record('warning', 2, permitted=lambda: True)
|
||||
assert len(store.snapshot()['events']) == 2
|
||||
clock[0] += 601000000000
|
||||
assert [event['eventId'] for event in store.snapshot()['events']] == [real.event_id]
|
||||
assert not (store.root / (fake.event_id + '.json')).exists()
|
||||
assert not (store.root / fake.event_id).exists()
|
||||
|
||||
Reference in New Issue
Block a user