mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 03:03:41 +08:00
StarPort: Ask for one tap to set up touch on cars that report video pixels
This commit is contained in:
@@ -166,7 +166,7 @@ def run(frames_path: str, touch_path: str | None = None, control_path: str | Non
|
||||
from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS, ProjectionControlSender
|
||||
from openpilot.starpilot.system.starport.projection_bookmark import BookmarkSender, request_bookmark
|
||||
from openpilot.starpilot.system.starport.projection_onroad import ProjectionOnroad
|
||||
from openpilot.starpilot.system.starport.touch import TouchReceiver, DEFAULT_TOUCH_SOCKET
|
||||
from openpilot.starpilot.system.starport.touch import TOUCH_SETUP_DOT, TouchReceiver, DEFAULT_TOUCH_SOCKET
|
||||
from openpilot.starpilot.ui.raylib import rl
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
@@ -269,6 +269,10 @@ def run(frames_path: str, touch_path: str | None = None, control_path: str | Non
|
||||
in_flight_camera = None
|
||||
|
||||
async_failures = 0
|
||||
touch_setup_until = 0.0
|
||||
touch_done_until = 0.0
|
||||
setup_dot = ((TOUCH_SETUP_DOT[0] * geometry.width - left) / geometry.scale,
|
||||
(TOUCH_SETUP_DOT[1] * geometry.height - top) / geometry.scale)
|
||||
|
||||
def publish_readback() -> None:
|
||||
"""Hand the frame read back last to starportd.
|
||||
@@ -374,11 +378,22 @@ def run(frames_path: str, touch_path: str | None = None, control_path: str | Non
|
||||
rl.rl_translatef(left, top, 0)
|
||||
rl.rl_scalef(geometry.scale, geometry.scale, 1.0)
|
||||
layout.render()
|
||||
if now < touch_setup_until:
|
||||
layout.draw_touch_setup(*setup_dot)
|
||||
elif now < touch_done_until:
|
||||
layout.draw_touch_setup(*setup_dot, done=True)
|
||||
finally:
|
||||
rl.rl_pop_matrix()
|
||||
finally:
|
||||
rl.end_texture_mode()
|
||||
layout.handle_touches(projected_touches(touch.drain(), geometry))
|
||||
touches = []
|
||||
for event in touch.drain():
|
||||
if event.kind == 'setup':
|
||||
touch_setup_until = now + 7.0 if event.x else 0.0
|
||||
touch_done_until = now + 3.0 if event.y else 0.0
|
||||
else:
|
||||
touches.append(event)
|
||||
layout.handle_touches(projected_touches(touches, geometry))
|
||||
if output is not None:
|
||||
gpu_nv12.compose_rgba(content.texture, output, request.margin_w, request.margin_h,
|
||||
content_left=request.content_left, content_top=request.content_top)
|
||||
|
||||
@@ -160,6 +160,7 @@ DEFAULT_CONFIG = {
|
||||
"auto_connect": True, # start projection on its own when the chosen car is on (onroad, or it reaches the comma)
|
||||
"rfcomm_cache": {}, # car address -> Android Auto RFCOMM channel learned over SDP, to skip discovery next time
|
||||
"modern_reply_cache": {}, # car address -> True when its v4+ head unit only started after the phone-style version reply
|
||||
"touch_units_cache": {}, # touch geometry -> "pixels" or "touchscreen": the units the car's touches arrive in
|
||||
"car_type": "", # wireless setup shown in Galaxy: "builtin" or "adapter"; "" = work it out from the saved companion car
|
||||
"car_profile_override": "", # "" = pick by fingerprint (a wireless adapter must choose); "default" = standard; otherwise a car_profiles id
|
||||
"car_fingerprint": {}, # what the chosen car's head unit reported last time, used to pick a profile before it connects
|
||||
@@ -219,6 +220,8 @@ def load_config(path: Path | None = None) -> dict:
|
||||
if type(channel) is int and 1 <= channel <= 30}
|
||||
config["modern_reply_cache"] = {str(address).upper(): True for address, modern in config["modern_reply_cache"].items()
|
||||
if modern is True}
|
||||
config["touch_units_cache"] = {str(key)[:64]: units for key, units in config["touch_units_cache"].items()
|
||||
if units in ("pixels", "touchscreen")}
|
||||
return config
|
||||
|
||||
|
||||
|
||||
@@ -639,6 +639,25 @@ class ProjectionOnroad:
|
||||
return claimed
|
||||
return gesture.claimed
|
||||
|
||||
def draw_touch_setup(self, x, y, done=False):
|
||||
"""One tap on this dot tells StarPort how the car reports touches."""
|
||||
rl, role = self.native.rl, self.native.font_role.BOLD
|
||||
if done:
|
||||
text, size = "Touch is set up", 64
|
||||
width = self.fonts.measure(text, role, size).width
|
||||
text_x = max(30, x - 90 - width)
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(text_x - 24, y - size / 2 - 16, width + 48, size + 32), .4, 8, rl.Color(15, 13, 23, 200))
|
||||
self.fonts.draw(text, role, size, text_x, y - size / 2)
|
||||
return
|
||||
rl.draw_circle(int(x), int(y), 56, rl.Color(15, 13, 23, 200))
|
||||
rl.draw_circle_lines(int(x), int(y), 56, rl.Color(199, 174, 247, 255))
|
||||
rl.draw_circle(int(x), int(y), 22, rl.Color(199, 174, 247, 255))
|
||||
text, size = "Tap the dot to set up touch", 64
|
||||
width = self.fonts.measure(text, role, size).width
|
||||
text_x = max(30, x - 90 - width)
|
||||
rl.draw_rectangle_rounded(rl.Rectangle(text_x - 24, y - size / 2 - 16, width + 48, size + 32), .4, 8, rl.Color(15, 13, 23, 200))
|
||||
self.fonts.draw(text, role, size, text_x, y - size / 2)
|
||||
|
||||
def cancel_touch(self):
|
||||
self.exit.cancel()
|
||||
if self.now_playing_touch is not None:
|
||||
|
||||
@@ -96,7 +96,8 @@ def forget_car(address: str, client: StarPortClient | None = None) -> bool:
|
||||
return False
|
||||
config.update(rfcomm_cache=cache, modern_reply_cache=replies)
|
||||
if chosen:
|
||||
config.update(receiver_address="", receiver_name="", companion_address="", companion_name="", car_fingerprint={})
|
||||
config.update(receiver_address="", receiver_name="", companion_address="", companion_name="", car_fingerprint={},
|
||||
touch_units_cache={})
|
||||
elif companion:
|
||||
config.update(companion_address="", companion_name="")
|
||||
identity.save_config(config)
|
||||
|
||||
@@ -750,6 +750,8 @@ class ProjectionSession(Session):
|
||||
self.audio = None # MediaAudio, attached by the supervisor when Spotify plays through Android Auto
|
||||
self.input_events = 0
|
||||
self.touch: TouchMapper | None = None
|
||||
self.touch_units: dict[str, str] = {} # touch geometry -> saved "pixels" or "touchscreen"
|
||||
self.on_touch_units: Callable[[str, str], None] | None = None
|
||||
self.touch_events: deque[TouchEvent] = deque(maxlen=128)
|
||||
self.keys = KeyTracker()
|
||||
self.media_control: Callable[[str], None] | None = None # non-blocking; set by the supervisor
|
||||
@@ -816,13 +818,19 @@ class ProjectionSession(Session):
|
||||
if self.mode is not None:
|
||||
self.touch = TouchMapper(config, self.mode.width, self.mode.height, self.mode.margin_width, self.mode.margin_height,
|
||||
content_left=self.mode.content_left, content_top=self.mode.content_top)
|
||||
if self.touch.content_space:
|
||||
saved = self.touch_units.get(self.touch.key)
|
||||
self.touch.content_pixels = saved != "touchscreen"
|
||||
self.touch.calibrating = saved is None
|
||||
self.event("input_opened", channel=channel["id"], keycodes=list(config.keycodes),
|
||||
touch=f"{config.touch_width}x{config.touch_height}", display_id=channel.get("display_id"),
|
||||
mapping={"touch_width": self.touch.touch_width, "touch_height": self.touch.touch_height,
|
||||
"video_width": self.touch.video_width, "video_height": self.touch.video_height,
|
||||
"content_left": self.touch.left, "content_top": self.touch.top,
|
||||
"content_width": self.touch.content_width, "content_height": self.touch.content_height,
|
||||
"content_space": self.touch.content_space} if self.touch is not None else None)
|
||||
"content_space": self.touch.content_space,
|
||||
"content_pixels": self.touch.content_pixels, "key": self.touch.key,
|
||||
"touch_setup": self.touch.calibrating} if self.touch is not None else None)
|
||||
except (TimeoutError, ValueError) as error:
|
||||
self.event("input_unavailable", channel=channel["id"], error=str(error))
|
||||
|
||||
@@ -982,10 +990,22 @@ class ProjectionSession(Session):
|
||||
disposition = "no_mapper" if self.touch is None else "unfocused" if not self.focused else "no_touch_event"
|
||||
if self.touch is not None and self.focused:
|
||||
try:
|
||||
switched, calibrating = self.touch.units_switched, self.touch.calibrating
|
||||
mapped = self.touch.decode(data)
|
||||
units = "touchscreen" if self.touch.units_switched and not switched else \
|
||||
self.touch.calibrated if calibrating and not self.touch.calibrating else None
|
||||
if units is not None:
|
||||
self.event("touch_units_switched" if switched != self.touch.units_switched else "touch_setup_done",
|
||||
channel=channel, units=units, key=self.touch.key)
|
||||
if self.on_touch_units is not None:
|
||||
self.on_touch_units(self.touch.key, units)
|
||||
if calibrating:
|
||||
mapped = [TouchEvent("setup", 0.0, 1.0)] # setup done: show the confirmation
|
||||
self.touch_events.extend(mapped)
|
||||
if mapped:
|
||||
disposition = "queued"
|
||||
elif calibrating:
|
||||
disposition = "touch_setup"
|
||||
except ValueError as error:
|
||||
disposition = "invalid"
|
||||
self.event("input_invalid", channel=channel, kind=kind, error=str(error))
|
||||
|
||||
@@ -43,7 +43,7 @@ from openpilot.starpilot.system.starport.bugsink_report import PairingAttempt
|
||||
from openpilot.starpilot.system.starport.frame_source import (DEFAULT_PATH as DEFAULT_FRAME_PATH, FLAG_ASYNC_READBACK, FLAG_NV12,
|
||||
FORMAT_NV12, FrameRequest)
|
||||
from openpilot.starpilot.system.starport.projection_control import DEFAULT_CONTROL_SOCKET, NATIVE_FOCUS
|
||||
from openpilot.starpilot.system.starport.touch import DEFAULT_TOUCH_SOCKET
|
||||
from openpilot.starpilot.system.starport.touch import DEFAULT_TOUCH_SOCKET, TouchEvent
|
||||
from openpilot.starpilot.system.starport.view import CAR_FRAME_PATH, ViewSource, renderer_available
|
||||
from openpilot.starpilot.system.starport.session import CODEC_H265, AuthenticationRejected, PeerRequestedStop, ProjectionSession, SharedRadioStall
|
||||
|
||||
@@ -737,7 +737,8 @@ class Supervisor:
|
||||
if chosen:
|
||||
if self._bluez is not None:
|
||||
self._bluez.release()
|
||||
self.config.update(receiver_address="", receiver_name="", companion_address="", companion_name="", car_fingerprint={})
|
||||
self.config.update(receiver_address="", receiver_name="", companion_address="", companion_name="", car_fingerprint={},
|
||||
touch_units_cache={})
|
||||
elif companion:
|
||||
self.config.update(companion_address="", companion_name="")
|
||||
identity_store.save_config(self.config)
|
||||
@@ -757,6 +758,9 @@ class Supervisor:
|
||||
self._quirks.reset(key)
|
||||
self._quirks.save()
|
||||
reset = reset or had_fix_state
|
||||
if address and self.config.get("touch_units_cache"):
|
||||
self.config["touch_units_cache"] = {}
|
||||
reset = True
|
||||
if reset:
|
||||
self._strategy = None
|
||||
self.config["modern_reply_cache"] = replies
|
||||
@@ -862,6 +866,15 @@ class Supervisor:
|
||||
identity_store.save_config(self.config)
|
||||
self.log("car_profile_selected", profile=profile or "auto")
|
||||
|
||||
def _remember_touch_units(self, key: str, units: str) -> None:
|
||||
with self._lock:
|
||||
cache = dict(self.config.get("touch_units_cache", {}))
|
||||
if cache.get(key) == units:
|
||||
return
|
||||
cache[key] = units
|
||||
self.config["touch_units_cache"] = cache
|
||||
identity_store.save_config(self.config)
|
||||
|
||||
def _remember_fingerprint(self, head_unit: dict) -> None:
|
||||
fingerprint = car_profiles.fingerprint_from(head_unit, self.config["receiver_address"])
|
||||
if fingerprint and fingerprint != self.config.get("car_fingerprint"):
|
||||
@@ -2082,6 +2095,8 @@ class Supervisor:
|
||||
self._stage("negotiating")
|
||||
self._fix_context = None
|
||||
session.on_discovered = self._choose_fixes
|
||||
session.touch_units = dict(config.get("touch_units_cache", {}))
|
||||
session.on_touch_units = self._remember_touch_units
|
||||
mode = session.start(config["device_name"], "comma.ai")
|
||||
self._set(mode=mode.as_dict(), error="")
|
||||
self.log("projection_ready", mode=mode.as_dict(), head_unit_subject=session.head_unit_subject)
|
||||
@@ -2248,6 +2263,7 @@ class Supervisor:
|
||||
started = time.monotonic()
|
||||
last_fresh = time.monotonic()
|
||||
last_unavailable = 0.0
|
||||
touch_setup_sent = 0.0
|
||||
next_check = 0.0
|
||||
ages: deque[float] = deque(maxlen=120)
|
||||
sent_times: deque[float] = deque(maxlen=200)
|
||||
@@ -2296,6 +2312,10 @@ class Supervisor:
|
||||
source.demand(1.0)
|
||||
else:
|
||||
source.release_demand()
|
||||
touch = getattr(session, "touch", None)
|
||||
if touch is not None and touch.calibrating and session.focused and now - touch_setup_sent >= 1.0:
|
||||
session.touch_events.append(TouchEvent("setup", 1.0, 0.0)) # the car view shows the dot while these keep coming
|
||||
touch_setup_sent = now
|
||||
if session.touch_events:
|
||||
source.send_touches(list(session.touch_events))
|
||||
session.touch_events.clear()
|
||||
|
||||
@@ -102,3 +102,51 @@ def test_offline_forget_clears_reply_strategy_and_fingerprint(sup):
|
||||
assert ADAPTER not in ladder.cars and OTHER in ladder.cars
|
||||
assert protocol.forget_car(OTHER, client) is False
|
||||
assert saved()["modern_reply_cache"] == {} and not SetupLadder(sup._ladder.path).cars
|
||||
|
||||
|
||||
def test_learned_touch_units_are_saved_and_survive_a_reload(sup):
|
||||
sup._remember_touch_units("1200x1244@1280x720-585x0", "touchscreen")
|
||||
sup._remember_touch_units("1920x720@1280x720-0x240", "pixels")
|
||||
assert saved()["touch_units_cache"] == {"1200x1244@1280x720-585x0": "touchscreen", "1920x720@1280x720-0x240": "pixels"}
|
||||
assert identity_store.load_config()["touch_units_cache"] == saved()["touch_units_cache"]
|
||||
|
||||
|
||||
def test_setup_tap_is_asked_once_then_remembered_across_reconnects(sup):
|
||||
from openpilot.starpilot.system.starport.tests.test_media_controls import session_with_input
|
||||
from openpilot.starpilot.system.starport.tests.test_touch import FORD, ford_session, tap
|
||||
|
||||
def connect():
|
||||
session = session_with_input(True)
|
||||
ford_session(session, dict(identity_store.load_config()["touch_units_cache"]))
|
||||
session.on_touch_units = sup._remember_touch_units
|
||||
return session
|
||||
|
||||
first = connect()
|
||||
assert first.touch.calibrating
|
||||
tap(first, 646, 648)
|
||||
assert not first.touch.calibrating and saved()["touch_units_cache"] == {FORD: "pixels"}
|
||||
for _ in range(3):
|
||||
again = connect()
|
||||
assert not again.touch.calibrating and again.touch.content_pixels
|
||||
tap(again, 646, 648)
|
||||
assert [event.kind for event in again.touch_events] == ["down", "up"]
|
||||
|
||||
|
||||
def test_forgetting_the_chosen_car_or_resetting_its_handshake_asks_for_the_touch_tap_again(sup):
|
||||
sup._remember_touch_units("1200x1244@1280x720-585x0", "pixels")
|
||||
assert sup.reset_handshake() is True
|
||||
assert sup.config["touch_units_cache"] == saved()["touch_units_cache"] == {}
|
||||
sup._remember_touch_units("1200x1244@1280x720-585x0", "pixels")
|
||||
assert daemon.handle(sup, {"command": "forget_receiver", "address": CAR}) == {"cleared": False}
|
||||
assert saved()["touch_units_cache"] != {} # a companion is not the car whose screen was set up
|
||||
daemon.handle(sup, {"command": "forget_receiver", "address": ADAPTER})
|
||||
assert sup.config["touch_units_cache"] == saved()["touch_units_cache"] == {}
|
||||
|
||||
|
||||
def test_offline_forget_of_the_chosen_car_clears_touch_setup(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(identity_store, "CONFIG_PATH", tmp_path / "config.json")
|
||||
identity_store.save_config({**identity_store.DEFAULT_CONFIG, "receiver_address": ADAPTER,
|
||||
"touch_units_cache": {"1920x720@1280x720-0x240": "touchscreen"}})
|
||||
client = protocol.StarPortClient(socket_path=str(tmp_path / "missing.sock"))
|
||||
assert protocol.forget_car(ADAPTER, client) is True
|
||||
assert saved()["touch_units_cache"] == {}
|
||||
|
||||
@@ -6,6 +6,7 @@ from openpilot.starpilot.system.starport.frame_source import FrameConsumer, Fram
|
||||
from openpilot.starpilot.system.starport.hw_encoder import HardwareH264Encoder, HardwareHevcEncoder
|
||||
from openpilot.starpilot.system.starport.projection_geometry import projection_geometry
|
||||
from openpilot.starpilot.system.starport.session import CODEC_H265, choose_video_mode
|
||||
from openpilot.starpilot.system.starport.tests.test_touch import packet
|
||||
from openpilot.starpilot.system.starport.touch import InputConfig, TouchMapper
|
||||
|
||||
|
||||
@@ -64,13 +65,25 @@ def test_hardware_encoders_accept_portrait_and_reject_oversized(encoder, tmp_pat
|
||||
|
||||
def test_touch_reported_over_the_visible_area_maps_to_the_whole_picture():
|
||||
mapper = TouchMapper(InputConfig((), 1152, 1182), 720, 1280, 0, 541)
|
||||
assert mapper.content_space
|
||||
assert mapper.content_space and mapper.content_pixels
|
||||
assert [(e.kind, e.x, e.y) for e in mapper.decode(packet(0, 1000, 1000))] == [('down', pytest.approx(1000 / 1152), pytest.approx(1000 / 1182))]
|
||||
assert mapper.units_switched and not mapper.content_pixels
|
||||
assert mapper._normalize(0, 0) == (0, 0)
|
||||
assert mapper._normalize(1152, 1182) == (1, 1)
|
||||
assert mapper._normalize(576, 591) == pytest.approx((0.5, 0.5))
|
||||
assert mapper._inside(0, 0) and mapper._inside(1151, 1181)
|
||||
|
||||
|
||||
def test_ford_touch_in_visible_video_pixels():
|
||||
# Mach-E advertises 1200x1244 but its taps span the 695x720 visible video.
|
||||
mapper = TouchMapper(InputConfig((), 1200, 1244), 1280, 720, 585, 0, content_left=292, content_top=0)
|
||||
for x, y in ((18, 23), (675, 22), (679, 707), (19, 698), (357, 373)):
|
||||
down = mapper.decode(packet(0, x, y))
|
||||
assert [(e.kind, e.x, e.y) for e in down] == [('down', pytest.approx(x / 695), pytest.approx(y / 720))]
|
||||
mapper.decode(packet(1, x, y))
|
||||
assert mapper.content_pixels and not mapper.units_switched
|
||||
|
||||
|
||||
def test_touch_reported_over_the_whole_frame_is_unchanged():
|
||||
mapper = TouchMapper(InputConfig((), 1280, 720), 1280, 720, 0, 240)
|
||||
assert not mapper.content_space
|
||||
|
||||
@@ -113,3 +113,65 @@ def test_failed_input_channel_is_identified(session):
|
||||
def test_binding_response_includes_channel(session):
|
||||
session.handle(3, INPUT_BINDING_RESPONSE, field(1, 0))
|
||||
assert session.events == [('input_bound', {'channel': 3, 'status': 0})]
|
||||
|
||||
|
||||
|
||||
FORD = '1200x1244@1280x720-585x0'
|
||||
|
||||
|
||||
def ford_session(session, units=None):
|
||||
session.channels = [{'id': 3, 'input': True, 'display_id': 0, 'input_config': InputConfig((), 1200, 1244)}]
|
||||
session.mode = VideoMode(1, 1, 1280, 720, 30, 585, 0)
|
||||
session.send = Mock()
|
||||
session.wait_for = Mock(return_value=field(1, 0))
|
||||
session.touch_units = units or {}
|
||||
session.on_touch_units = Mock()
|
||||
session.open_input()
|
||||
return session
|
||||
|
||||
|
||||
def tap(session, x, y):
|
||||
session.handle(3, INPUT_EVENT, packet(0, x, y))
|
||||
session.handle(3, INPUT_EVENT, packet(1, x, y))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('dot, units', [((646, 648), 'pixels'), ((1116, 1120), 'touchscreen')])
|
||||
def test_first_connection_asks_for_one_tap_on_the_dot(session, dot, units):
|
||||
ford_session(session)
|
||||
assert session.touch.calibrating
|
||||
assert next(v for n, v in session.events if n == 'input_opened')['mapping']['touch_setup'] is True
|
||||
tap(session, 300, 300) # not on the dot: swallowed, still asking
|
||||
assert session.touch.calibrating and session.touch_events == []
|
||||
tap(session, *dot)
|
||||
assert not session.touch.calibrating
|
||||
session.on_touch_units.assert_called_once_with(FORD, units)
|
||||
assert ('touch_setup_done', {'channel': 3, 'units': units, 'key': FORD}) in session.events
|
||||
assert list(session.touch_events) == [TouchEvent('setup', 0.0, 1.0)]
|
||||
assert session.touch.content_pixels == (units == 'pixels')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('touch, video, margin, units', [
|
||||
((1152, 1182), (1080, 1920), 811, 'pixels'), ((1152, 1182), (1080, 1920), 811, 'touchscreen'),
|
||||
((1920, 720), (1280, 720), 240, 'pixels'), ((1920, 720), (1280, 720), 240, 'touchscreen')])
|
||||
def test_setup_tap_tells_units_apart_on_other_cars(touch, video, margin, units):
|
||||
mapper = TouchMapper(InputConfig((), touch[0], touch[1]), video[0], video[1], 0, margin)
|
||||
mapper.calibrating = True
|
||||
width, height = (mapper.content_width, mapper.content_height) if units == 'pixels' else touch
|
||||
assert mapper.decode(packet(0, round(.93 * width) + 15, round(.90 * height) - 15)) == []
|
||||
assert mapper.calibrated == units and not mapper.calibrating
|
||||
|
||||
|
||||
def test_saved_pixels_skip_setup_but_a_touch_past_them_still_switches(session):
|
||||
ford_session(session, {FORD: 'pixels'})
|
||||
assert not session.touch.calibrating and session.touch.content_pixels
|
||||
tap(session, 1100, 1200)
|
||||
session.on_touch_units.assert_called_once_with(FORD, 'touchscreen')
|
||||
assert sum(name == 'touch_units_switched' for name, _ in session.events) == 1
|
||||
|
||||
|
||||
def test_remembered_touchscreen_units_apply_from_the_first_touch(session):
|
||||
ford_session(session, {FORD: 'touchscreen'})
|
||||
assert not session.touch.calibrating and not session.touch.content_pixels
|
||||
session.handle(3, INPUT_EVENT, packet(0, 600, 622))
|
||||
assert session.touch_events == [TouchEvent('down', .5, .5)]
|
||||
session.on_touch_units.assert_not_called()
|
||||
|
||||
@@ -27,6 +27,8 @@ ACTION_POINTER_UP = 6
|
||||
MAX_INPUT_BYTES = 16 * 1024
|
||||
MAX_KEYCODES = 256
|
||||
DEFAULT_TOUCH_SOCKET = "/tmp/starpilot-starport-touch.sock"
|
||||
TOUCH_SETUP_DOT = (0.93, 0.90) # where the car view asks for the one setup tap, normalized in the visible area
|
||||
TOUCH_SETUP_REACH = 0.12
|
||||
MEDIA_KEYS = {85: "play_pause", 87: "next", 88: "previous", 126: "play", 127: "pause"}
|
||||
|
||||
|
||||
@@ -94,11 +96,36 @@ class TouchMapper:
|
||||
self.pointer: int | None = None
|
||||
self.content_space = bool(margin_width or margin_height) and self._same_shape(self.content_width, self.content_height) \
|
||||
and not self._same_shape(video_width, video_height)
|
||||
# Some head units report visible-video pixels, not their advertised touch size.
|
||||
self.content_pixels = self.content_space
|
||||
self.units_switched = False
|
||||
self.calibrating = False
|
||||
self.calibrated: str | None = None
|
||||
self.key = f"{self.touch_width}x{self.touch_height}@{video_width}x{video_height}-{margin_width}x{margin_height}"
|
||||
|
||||
def _same_shape(self, width: int, height: int) -> bool:
|
||||
return abs(self.touch_width * height / (self.touch_height * width) - 1) < 0.02
|
||||
|
||||
def _check_units(self, locations) -> None:
|
||||
if self.content_pixels and any(x > self.content_width or y > self.content_height for _, x, y in locations):
|
||||
self.content_pixels = False
|
||||
self.units_switched = True
|
||||
|
||||
def _calibrate(self, x: int, y: int) -> None:
|
||||
"""Read the setup tap both ways; the reading nearer the dot names the units."""
|
||||
dx, dy = TOUCH_SETUP_DOT
|
||||
pixels = ((x / self.content_width - dx) ** 2 + (y / self.content_height - dy) ** 2) ** 0.5
|
||||
panel = ((x / self.touch_width - dx) ** 2 + (y / self.touch_height - dy) ** 2) ** 0.5
|
||||
exceeded = x > self.content_width or y > self.content_height
|
||||
units = "touchscreen" if exceeded or panel < pixels else "pixels"
|
||||
if (panel if units == "touchscreen" else pixels) > TOUCH_SETUP_REACH:
|
||||
return # not a tap on the dot: keep asking
|
||||
self.content_pixels = units == "pixels"
|
||||
self.calibrating, self.calibrated = False, units
|
||||
|
||||
def _video_point(self, x: int, y: int) -> tuple[float, float]:
|
||||
if self.content_pixels:
|
||||
return self.left + x, self.top + y
|
||||
if self.content_space:
|
||||
return self.left + x * self.content_width / self.touch_width, self.top + y * self.content_height / self.touch_height
|
||||
return x * self.video_width / self.touch_width, y * self.video_height / self.touch_height
|
||||
@@ -136,6 +163,11 @@ class TouchMapper:
|
||||
index = int(one(fields, 2, 0) or 0)
|
||||
if not locations:
|
||||
return []
|
||||
if self.calibrating:
|
||||
if action == ACTION_PRESS:
|
||||
self._calibrate(locations[0][1], locations[0][2])
|
||||
return []
|
||||
self._check_units(locations)
|
||||
events: list[TouchEvent] = []
|
||||
if action == ACTION_PRESS and self.pointer is None:
|
||||
pointer, x, y = locations[0]
|
||||
@@ -229,7 +261,7 @@ class TouchReceiver:
|
||||
kind, x, y = str(raw["kind"]), float(raw["x"]), float(raw["y"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
continue
|
||||
if kind in ("down", "move", "up", "cancel") and 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0:
|
||||
if kind in ("down", "move", "up", "cancel", "setup") and 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0:
|
||||
events.append(TouchEvent(kind, x, y))
|
||||
return events
|
||||
|
||||
|
||||
Reference in New Issue
Block a user