-
Notifications
You must be signed in to change notification settings - Fork 308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pairing agent #1100
Draft
dlech
wants to merge
3
commits into
develop
Choose a base branch
from
pairing-agent
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Pairing agent #1100
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import abc | ||
from typing import Optional | ||
|
||
from .backends.device import BLEDevice | ||
|
||
|
||
class BaseBleakAgentCallbacks(abc.ABC): | ||
@abc.abstractmethod | ||
async def confirm(self, device: BLEDevice) -> bool: | ||
""" | ||
Implementers should prompt the user to confirm or reject the pairing | ||
request. | ||
|
||
Returns: | ||
``True`` to accept the pairing request or ``False`` to reject it. | ||
""" | ||
|
||
@abc.abstractmethod | ||
async def confirm_pin(self, device: BLEDevice, pin: str) -> bool: | ||
""" | ||
Implementers should display the pin code to the user and prompt the | ||
user to validate the pin code and confirm or reject the pairing request. | ||
|
||
Args: | ||
pin: The pin code to be confirmed. | ||
|
||
Returns: | ||
``True`` to accept the pairing request or ``False`` to reject it. | ||
""" | ||
|
||
@abc.abstractmethod | ||
async def display_pin(self, device: BLEDevice, pin: str) -> None: | ||
""" | ||
Implementers should display the pin code to the user. | ||
|
||
This method should block indefinitely until it canceled (i.e. | ||
``await asyncio.Event().wait()``). | ||
|
||
Args: | ||
pin: The pin code to be confirmed. | ||
""" | ||
|
||
@abc.abstractmethod | ||
async def request_pin(self, device: BLEDevice) -> Optional[str]: | ||
""" | ||
Implementers should prompt the user to enter a pin code to accept the | ||
pairing request or to reject the paring request. | ||
|
||
Returns: | ||
A string containing the pin code to accept the pairing request or | ||
``None`` to reject it. | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
""" | ||
Agent | ||
----- | ||
|
||
This module contains types associated with the BlueZ D-Bus `agent api | ||
<https://github.com/bluez/bluez/blob/master/doc/agent-api.txt>`. | ||
""" | ||
|
||
import asyncio | ||
import contextlib | ||
import logging | ||
import os | ||
from typing import Set, no_type_check | ||
|
||
from dbus_fast import DBusError, Message | ||
from dbus_fast.aio import MessageBus | ||
from dbus_fast.service import ServiceInterface, method | ||
|
||
from bleak.backends.device import BLEDevice | ||
|
||
from ...agent import BaseBleakAgentCallbacks | ||
from . import defs | ||
from .manager import get_global_bluez_manager | ||
from .utils import assert_reply | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class Agent(ServiceInterface): | ||
""" | ||
Implementation of the org.bluez.Agent1 D-Bus interface. | ||
""" | ||
|
||
def __init__(self, callbacks: BaseBleakAgentCallbacks): | ||
""" | ||
Args: | ||
""" | ||
super().__init__(defs.AGENT_INTERFACE) | ||
self._callbacks = callbacks | ||
self._tasks: Set[asyncio.Task] = set() | ||
|
||
async def _create_ble_device(self, device_path: str) -> BLEDevice: | ||
manager = await get_global_bluez_manager() | ||
props = manager.get_device_props(device_path) | ||
return BLEDevice( | ||
props["Address"], props["Alias"], {"path": device_path, "props": props} | ||
) | ||
|
||
@method() | ||
def Release(self): | ||
logger.debug("Release") | ||
|
||
# REVISIT: mypy is broke, so we have to add redundant @no_type_check | ||
# https://github.com/python/mypy/issues/6583 | ||
|
||
@method() | ||
@no_type_check | ||
async def RequestPinCode(self, device: "o") -> "s": # noqa: F821 | ||
logger.debug("RequestPinCode %s", device) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
async def DisplayPinCode(self, device: "o", pincode: "s"): # noqa: F821 | ||
logger.debug("DisplayPinCode %s %s", device, pincode) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
async def RequestPasskey(self, device: "o") -> "u": # noqa: F821 | ||
logger.debug("RequestPasskey %s", device) | ||
|
||
ble_device = await self._create_ble_device(device) | ||
|
||
task = asyncio.create_task(self._callbacks.request_pin(ble_device)) | ||
self._tasks.add(task) | ||
|
||
try: | ||
pin = await task | ||
except asyncio.CancelledError: | ||
raise DBusError("org.bluez.Error.Canceled", "task canceled") | ||
finally: | ||
self._tasks.remove(task) | ||
|
||
if not pin: | ||
raise DBusError("org.bluez.Error.Rejected", "user rejected") | ||
|
||
return int(pin) | ||
|
||
@method() | ||
@no_type_check | ||
async def DisplayPasskey( | ||
self, device: "o", passkey: "u", entered: "q" # noqa: F821 | ||
): | ||
passkey = f"{passkey:06}" | ||
logger.debug("DisplayPasskey %s %s %d", device, passkey, entered) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
async def RequestConfirmation(self, device: "o", passkey: "u"): # noqa: F821 | ||
passkey = f"{passkey:06}" | ||
logger.debug("RequestConfirmation %s %s", device, passkey) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
async def RequestAuthorization(self, device: "o"): # noqa: F821 | ||
logger.debug("RequestAuthorization %s", device) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
async def AuthorizeService(self, device: "o", uuid: "s"): # noqa: F821 | ||
logger.debug("AuthorizeService %s", device, uuid) | ||
raise NotImplementedError | ||
|
||
@method() | ||
@no_type_check | ||
def Cancel(self): # noqa: F821 | ||
logger.debug("Cancel") | ||
for t in self._tasks: | ||
t.cancel() | ||
|
||
|
||
@contextlib.asynccontextmanager | ||
async def bluez_agent(bus: MessageBus, callbacks: BaseBleakAgentCallbacks): | ||
agent = Agent(callbacks) | ||
|
||
# REVISIT: implement passing capability if needed | ||
# "DisplayOnly", "DisplayYesNo", "KeyboardOnly", "NoInputNoOutput", "KeyboardDisplay" | ||
capability = "" | ||
|
||
# this should be a unique path to allow multiple python interpreters | ||
# running bleak and multiple agents at the same time | ||
agent_path = f"/org/bleak/agent/{os.getpid()}/{id(agent)}" | ||
|
||
bus.export(agent_path, agent) | ||
|
||
try: | ||
reply = await bus.call( | ||
Message( | ||
destination=defs.BLUEZ_SERVICE, | ||
path="/org/bluez", | ||
interface=defs.AGENT_MANAGER_INTERFACE, | ||
member="RegisterAgent", | ||
signature="os", | ||
body=[agent_path, capability], | ||
) | ||
) | ||
|
||
assert_reply(reply) | ||
|
||
try: | ||
yield | ||
finally: | ||
reply = await bus.call( | ||
Message( | ||
destination=defs.BLUEZ_SERVICE, | ||
path="/org/bluez", | ||
interface=defs.AGENT_MANAGER_INTERFACE, | ||
member="UnregisterAgent", | ||
signature="o", | ||
body=[agent_path], | ||
) | ||
) | ||
|
||
assert_reply(reply) | ||
|
||
finally: | ||
bus.unexport(agent_path, agent) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
because of bcae937#diff-d647d8e3f316fd939334bd8ed60d248095c8a6f69bc73dd0b369867609dc00a6R21