diff --git a/homeassistant/components/keyboard_remote/__init__.py b/homeassistant/components/keyboard_remote/__init__.py index 420bd72891b6..b3b316ebe6ef 100644 --- a/homeassistant/components/keyboard_remote/__init__.py +++ b/homeassistant/components/keyboard_remote/__init__.py @@ -36,10 +36,12 @@ from .const import ( CONF_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT, + CONF_EXCLUSIVE, CONF_KEY_TYPES, DEFAULT_EMULATE_KEY_HOLD, DEFAULT_EMULATE_KEY_HOLD_DELAY, DEFAULT_EMULATE_KEY_HOLD_REPEAT, + DEFAULT_EXCLUSIVE, DEFAULT_KEY_TYPES, DEVINPUT, DEVINPUT_BY_ID, @@ -199,6 +201,21 @@ async def async_setup_entry( entry.async_on_unload(async_at_start(hass, _async_start)) +async def async_migrate_entry( + hass: HomeAssistant, entry: KeyboardRemoteConfigEntry +) -> None: + """Migrate an old config entry.""" + if entry.minor_version < 2: + # Entries created before the exclusive option existed always grabbed + # the device, which the default keeps. An entry that already carries + # the option was set up with it and must not be flipped to grabbing. + hass.config_entries.async_update_entry( + entry, + options={CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, **entry.options}, + minor_version=2, + ) + + async def async_unload_entry( hass: HomeAssistant, entry: KeyboardRemoteConfigEntry ) -> None: @@ -799,6 +816,7 @@ class DeviceHandler: # this handler exists. options = entry.options self._key_values = {KEY_VALUE[key_type] for key_type in options[CONF_KEY_TYPES]} + self._exclusive: bool = options[CONF_EXCLUSIVE] self._emulate_key_hold: bool = options[CONF_EMULATE_KEY_HOLD] self._emulate_key_hold_delay: float = options[CONF_EMULATE_KEY_HOLD_DELAY] self._emulate_key_hold_repeat: float = options[CONF_EMULATE_KEY_HOLD_REPEAT] @@ -921,7 +939,8 @@ class DeviceHandler: Pass from_monitor_task=True when the monitor task itself is tearing down after a read failure. It cannot wait for its own completion, and - ungrabbing a device that just errored would only raise again. + ungrabbing a device that just errored would only raise again. A device + monitored non-exclusively was never grabbed, so it is not ungrabbed. """ if (task := self._monitor_task) is None: return @@ -937,7 +956,7 @@ class DeviceHandler: self._monitor_task = None try: - if not from_monitor_task: + if not from_monitor_task and self._exclusive: with suppress(OSError): await self.hass.async_add_executor_job(dev.ungrab) finally: @@ -1002,16 +1021,19 @@ class DeviceHandler: from evdev import ecodes # noqa: PLC0415 try: - _LOGGER.debug("Start device monitoring") - try: - await self.hass.async_add_executor_job(dev.grab) - except OSError as err: - _LOGGER.warning( - "Unable to grab %s, it may be in use by another program: %s", - dev.name, - err, + if self._exclusive: + _LOGGER.debug( + "Start exclusive monitoring of %s (%s)", dev.name, dev.path + ) + try: + await self.hass.async_add_executor_job(dev.grab) + except OSError as err: + _LOGGER.warning("Unable to grab %s: %s", dev.name, err) + raise + else: + _LOGGER.debug( + "Start non-exclusive monitoring of %s (%s)", dev.name, dev.path ) - raise async for event in dev.async_read_loop(): if event.type == ecodes.EV_KEY: if event.value in self._key_values: diff --git a/homeassistant/components/keyboard_remote/config_flow.py b/homeassistant/components/keyboard_remote/config_flow.py index 9cf37a3f6227..98398e329a20 100644 --- a/homeassistant/components/keyboard_remote/config_flow.py +++ b/homeassistant/components/keyboard_remote/config_flow.py @@ -29,10 +29,12 @@ from .const import ( CONF_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT, + CONF_EXCLUSIVE, CONF_KEY_TYPES, DEFAULT_EMULATE_KEY_HOLD, DEFAULT_EMULATE_KEY_HOLD_DELAY, DEFAULT_EMULATE_KEY_HOLD_REPEAT, + DEFAULT_EXCLUSIVE, DEFAULT_KEY_TYPES, DEVINPUT_BY_ID, DOMAIN, @@ -234,6 +236,7 @@ class KeyboardRemoteConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Keyboard Remote.""" VERSION = 1 + MINOR_VERSION = 2 def __init__(self) -> None: """Initialize the flow.""" @@ -292,6 +295,7 @@ class KeyboardRemoteConfigFlow(ConfigFlow, domain=DOMAIN): data=data, options={ CONF_KEY_TYPES: DEFAULT_KEY_TYPES, + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: DEFAULT_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY: DEFAULT_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT: DEFAULT_EMULATE_KEY_HOLD_REPEAT, @@ -396,6 +400,7 @@ class KeyboardRemoteConfigFlow(ConfigFlow, domain=DOMAIN): data=data, options={ CONF_KEY_TYPES: key_types, + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: import_data[CONF_EMULATE_KEY_HOLD], CONF_EMULATE_KEY_HOLD_DELAY: _clamp_imported( CONF_EMULATE_KEY_HOLD_DELAY, @@ -504,6 +509,11 @@ class KeyboardRemoteOptionsFlow(OptionsFlowWithReload): mode=selector.SelectSelectorMode.LIST, ) ), + # Suggested values come from the entry options, which have + # no exclusive value until the entry is set up and migrated + probatio.Required( + CONF_EXCLUSIVE, default=DEFAULT_EXCLUSIVE + ): selector.BooleanSelector(), probatio.Required( CONF_EMULATE_KEY_HOLD, ): selector.BooleanSelector(), diff --git a/homeassistant/components/keyboard_remote/const.py b/homeassistant/components/keyboard_remote/const.py index 3da45d9f2bd2..44f7fe56511b 100644 --- a/homeassistant/components/keyboard_remote/const.py +++ b/homeassistant/components/keyboard_remote/const.py @@ -11,11 +11,14 @@ CONF_DEVICE_DESCRIPTOR: Final = "device_descriptor" CONF_DEVICE_UNIQ: Final = "device_uniq" CONF_KEY_TYPES: Final = "key_types" +# Whether to grab the device, so that no other program receives its events +CONF_EXCLUSIVE: Final = "exclusive" CONF_EMULATE_KEY_HOLD: Final = "emulate_key_hold" CONF_EMULATE_KEY_HOLD_DELAY: Final = "emulate_key_hold_delay" CONF_EMULATE_KEY_HOLD_REPEAT: Final = "emulate_key_hold_repeat" DEFAULT_KEY_TYPES: Final = ["key_up"] +DEFAULT_EXCLUSIVE: Final = True DEFAULT_EMULATE_KEY_HOLD: Final = False DEFAULT_EMULATE_KEY_HOLD_DELAY: Final = 0.250 DEFAULT_EMULATE_KEY_HOLD_REPEAT: Final = 0.033 diff --git a/homeassistant/components/keyboard_remote/strings.json b/homeassistant/components/keyboard_remote/strings.json index de01bc33c11e..010346782a38 100644 --- a/homeassistant/components/keyboard_remote/strings.json +++ b/homeassistant/components/keyboard_remote/strings.json @@ -37,12 +37,14 @@ "emulate_key_hold": "Emulate key hold", "emulate_key_hold_delay": "Key hold delay", "emulate_key_hold_repeat": "Key hold repeat interval", + "exclusive": "Exclusive access", "key_types": "Key event types" }, "data_description": { "emulate_key_hold": "Enable software emulation of key hold events.", "emulate_key_hold_delay": "Delay before key hold emulation starts.", "emulate_key_hold_repeat": "Repeat interval for emulated key hold events.", + "exclusive": "Grab the device so that no other program receives its key presses. Turn off to share it, for example a gamepad that is also used to play games.", "key_types": "Select which key events to listen for." }, "description": "Device: `{device}`", diff --git a/tests/components/keyboard_remote/conftest.py b/tests/components/keyboard_remote/conftest.py index 960c94952503..9a35baa47e3c 100644 --- a/tests/components/keyboard_remote/conftest.py +++ b/tests/components/keyboard_remote/conftest.py @@ -22,10 +22,12 @@ from homeassistant.components.keyboard_remote.const import ( CONF_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT, + CONF_EXCLUSIVE, CONF_KEY_TYPES, DEFAULT_EMULATE_KEY_HOLD, DEFAULT_EMULATE_KEY_HOLD_DELAY, DEFAULT_EMULATE_KEY_HOLD_REPEAT, + DEFAULT_EXCLUSIVE, DEFAULT_KEY_TYPES, DEVINPUT, DEVINPUT_BY_ID, @@ -78,6 +80,7 @@ def mock_config_entry() -> MockConfigEntry: }, options={ CONF_KEY_TYPES: DEFAULT_KEY_TYPES, + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: DEFAULT_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY: DEFAULT_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT: DEFAULT_EMULATE_KEY_HOLD_REPEAT, diff --git a/tests/components/keyboard_remote/test_config_flow.py b/tests/components/keyboard_remote/test_config_flow.py index 993096c82ea3..8b280158b20d 100644 --- a/tests/components/keyboard_remote/test_config_flow.py +++ b/tests/components/keyboard_remote/test_config_flow.py @@ -17,10 +17,12 @@ from homeassistant.components.keyboard_remote.const import ( CONF_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT, + CONF_EXCLUSIVE, CONF_KEY_TYPES, DEFAULT_EMULATE_KEY_HOLD, DEFAULT_EMULATE_KEY_HOLD_DELAY, DEFAULT_EMULATE_KEY_HOLD_REPEAT, + DEFAULT_EXCLUSIVE, DEFAULT_KEY_TYPES, DOMAIN, ) @@ -49,6 +51,7 @@ REMOTE_2_UNIQ = "aa:bb:cc:dd:ee:02" DEFAULT_OPTIONS = { CONF_KEY_TYPES: DEFAULT_KEY_TYPES, + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: DEFAULT_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY: DEFAULT_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT: DEFAULT_EMULATE_KEY_HOLD_REPEAT, @@ -465,6 +468,7 @@ async def test_import_with_descriptor_and_by_id( } assert result["options"] == { CONF_KEY_TYPES: ["key_up", "key_down"], + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: True, CONF_EMULATE_KEY_HOLD_DELAY: 0.5, CONF_EMULATE_KEY_HOLD_REPEAT: 0.05, @@ -900,6 +904,7 @@ async def test_options_flow( result["flow_id"], user_input={ CONF_KEY_TYPES: ["key_up", "key_down", "key_hold"], + CONF_EXCLUSIVE: False, CONF_EMULATE_KEY_HOLD: True, CONF_EMULATE_KEY_HOLD_DELAY: 0.5, CONF_EMULATE_KEY_HOLD_REPEAT: 0.05, @@ -910,6 +915,7 @@ async def test_options_flow( assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"] == { CONF_KEY_TYPES: ["key_up", "key_down", "key_hold"], + CONF_EXCLUSIVE: False, CONF_EMULATE_KEY_HOLD: True, CONF_EMULATE_KEY_HOLD_DELAY: 0.5, CONF_EMULATE_KEY_HOLD_REPEAT: 0.05, @@ -930,6 +936,7 @@ async def test_options_flow_requires_a_key_type( await hass.async_block_till_done() options = { CONF_KEY_TYPES: [], + CONF_EXCLUSIVE: True, CONF_EMULATE_KEY_HOLD: False, CONF_EMULATE_KEY_HOLD_DELAY: 0.5, CONF_EMULATE_KEY_HOLD_REPEAT: 0.05, @@ -952,6 +959,46 @@ async def test_options_flow_requires_a_key_type( assert result["data"][CONF_KEY_TYPES] == ["key_down"] +@pytest.mark.usefixtures("mock_setup_entry") +async def test_options_flow_defaults_to_exclusive_before_migration( + hass: HomeAssistant, +) -> None: + """Test the options form of an entry not migrated yet defaults to exclusive. + + An entry disabled since before the option existed is never set up, so it is + never migrated and its options hold no exclusive value to suggest. + """ + entry = MockConfigEntry( + domain=DOMAIN, + minor_version=1, + data={CONF_DEVICE_PATH: FAKE_DEVICE_PATH, CONF_DEVICE_NAME: FAKE_DEVICE_NAME}, + options={ + CONF_KEY_TYPES: DEFAULT_KEY_TYPES, + CONF_EMULATE_KEY_HOLD: DEFAULT_EMULATE_KEY_HOLD, + CONF_EMULATE_KEY_HOLD_DELAY: DEFAULT_EMULATE_KEY_HOLD_DELAY, + CONF_EMULATE_KEY_HOLD_REPEAT: DEFAULT_EMULATE_KEY_HOLD_REPEAT, + }, + ) + entry.add_to_hass(hass) + + result = await hass.config_entries.options.async_init(entry.entry_id) + + assert result["type"] is FlowResultType.FORM + exclusive = next( + key for key in result["data_schema"].schema if key == CONF_EXCLUSIVE + ) + assert exclusive.default() is DEFAULT_EXCLUSIVE + assert "suggested_value" not in (exclusive.description or {}) + + result = await hass.config_entries.options.async_configure( + result["flow_id"], user_input=dict(entry.options) + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == {**entry.options, CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE} + + @pytest.mark.parametrize( ("data", "expected_device"), [ diff --git a/tests/components/keyboard_remote/test_init.py b/tests/components/keyboard_remote/test_init.py index 8dfe18e1fee5..b92c26f72bd9 100644 --- a/tests/components/keyboard_remote/test_init.py +++ b/tests/components/keyboard_remote/test_init.py @@ -27,10 +27,12 @@ from homeassistant.components.keyboard_remote.const import ( CONF_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT, + CONF_EXCLUSIVE, CONF_KEY_TYPES, DEFAULT_EMULATE_KEY_HOLD, DEFAULT_EMULATE_KEY_HOLD_DELAY, DEFAULT_EMULATE_KEY_HOLD_REPEAT, + DEFAULT_EXCLUSIVE, DEFAULT_KEY_TYPES, DEVINPUT, DEVINPUT_BY_ID, @@ -73,6 +75,7 @@ OTHER_LINK = "/dev/input/by-id/usb-Other-event-kbd" OPTIONS = { CONF_KEY_TYPES: DEFAULT_KEY_TYPES, + CONF_EXCLUSIVE: DEFAULT_EXCLUSIVE, CONF_EMULATE_KEY_HOLD: DEFAULT_EMULATE_KEY_HOLD, CONF_EMULATE_KEY_HOLD_DELAY: DEFAULT_EMULATE_KEY_HOLD_DELAY, CONF_EMULATE_KEY_HOLD_REPEAT: DEFAULT_EMULATE_KEY_HOLD_REPEAT, @@ -986,6 +989,105 @@ async def test_unexpected_read_error_releases_device( assert mock_config_entry.state is ConfigEntryState.NOT_LOADED +@pytest.mark.parametrize( + ("options", "expected_grabbed", "expected_log"), + [ + pytest.param( + {CONF_EXCLUSIVE: True}, + True, + "Start exclusive monitoring of Test Keyboard (/dev/input/event5)", + id="exclusive", + ), + pytest.param( + {CONF_EXCLUSIVE: False}, + False, + "Start non-exclusive monitoring of Test Keyboard (/dev/input/event5)", + id="non_exclusive", + ), + ], +) +async def test_exclusive_option_decides_the_grab( + hass: HomeAssistant, + fake_input: FakeInput, + caplog: pytest.LogCaptureFixture, + options: dict[str, bool], + expected_grabbed: bool, + expected_log: str, +) -> None: + """Test the device is only grabbed when the entry is exclusive. + + Either way the device is read and released, and the mode is logged. + """ + kbd = fake_input.add(FAKE_DEVICE_REAL_PATH, FAKE_DEVICE_NAME, link=FAKE_DEVICE_PATH) + commands = async_capture_events(hass, EVENT_KEYBOARD_REMOTE_COMMAND_RECEIVED) + disconnected = async_capture_events(hass, EVENT_KEYBOARD_REMOTE_DISCONNECTED) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=FAKE_DEVICE_PATH, + data={CONF_DEVICE_PATH: FAKE_DEVICE_PATH, CONF_DEVICE_NAME: FAKE_DEVICE_NAME}, + options={ + **{key: value for key, value in OPTIONS.items() if key != CONF_EXCLUSIVE}, + **options, + }, + ) + + await _set_up(hass, fake_input, entry) + + assert kbd.grab.called is expected_grabbed + assert expected_log in caplog.text + + await fake_input.press(kbd, 30, KEY_VALUE["key_up"]) + + assert len(commands) == 1 + + await hass.config_entries.async_unload(entry.entry_id) + await fake_input.settle() + + assert kbd.ungrab.called is expected_grabbed + kbd.close.assert_called_once() + assert len(disconnected) == 1 + + +@pytest.mark.parametrize( + ("stored_options", "expected_exclusive"), + [ + pytest.param({}, DEFAULT_EXCLUSIVE, id="option_added"), + pytest.param({CONF_EXCLUSIVE: False}, False, id="stored_value_kept"), + ], +) +async def test_migration_adds_the_exclusive_option( + hass: HomeAssistant, + fake_input: FakeInput, + stored_options: dict[str, bool], + expected_exclusive: bool, +) -> None: + """Test an entry from before the exclusive option is migrated. + + Entries created by the first config flow release have no exclusive option. + The migration adds the default, so they keep grabbing the device, and + leaves a value a stored entry already carries alone. + """ + kbd = fake_input.add(FAKE_DEVICE_REAL_PATH, FAKE_DEVICE_NAME, link=FAKE_DEVICE_PATH) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=FAKE_DEVICE_PATH, + data={CONF_DEVICE_PATH: FAKE_DEVICE_PATH, CONF_DEVICE_NAME: FAKE_DEVICE_NAME}, + options={ + **{key: value for key, value in OPTIONS.items() if key != CONF_EXCLUSIVE}, + **stored_options, + }, + version=1, + minor_version=1, + ) + + await _set_up(hass, fake_input, entry) + + assert entry.state is ConfigEntryState.LOADED + assert entry.minor_version == 2 + assert entry.options[CONF_EXCLUSIVE] is expected_exclusive + assert kbd.grab.called is expected_exclusive + + async def test_grab_failure_warns_and_releases( hass: HomeAssistant, fake_input: FakeInput, @@ -999,9 +1101,7 @@ async def test_grab_failure_warns_and_releases( await _set_up(hass, fake_input, mock_config_entry) - assert "Unable to grab Test Keyboard, it may be in use by another program" in ( - caplog.text - ) + assert "Unable to grab Test Keyboard" in caplog.text kbd.close.assert_called_once() assert len(disconnected) == 1