Skip to content

Commit

Permalink
feat: implement Bluetooth Emulation BiDi mapping (#2624)
Browse files Browse the repository at this point in the history
Implements the Bluetooth Emulation spec from WebBluetoothCG/web-bluetooth#630.
  • Loading branch information
alexnj authored Oct 10, 2024
1 parent 615ab8e commit 48a233f
Show file tree
Hide file tree
Showing 4 changed files with 224 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/bidiMapper/CommandProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,16 @@ export class CommandProcessor extends EventEmitter<CommandProcessorEventsMap> {
return await this.#bluetoothProcessor.handleRequestDevicePrompt(
this.#parser.parseHandleRequestDevicePromptParams(command.params)
);
case 'bluetooth.simulateAdapter':
return await this.#bluetoothProcessor.simulateAdapter(command.params);
case 'bluetooth.simulateAdvertisement':
return await this.#bluetoothProcessor.simulateAdvertisement(
command.params
);
case 'bluetooth.simulatePreconnectedPeripheral':
return await this.#bluetoothProcessor.simulatePreconnectedPeripheral(
command.params
);
// keep-sorted end

// Browser domain
Expand Down
42 changes: 42 additions & 0 deletions src/bidiMapper/modules/bluetooth/BluetoothProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,48 @@ export class BluetoothProcessor {
this.#browsingContextStorage = browsingContextStorage;
}

async simulateAdapter(
params: Bluetooth.SimulateAdapterParameters
): Promise<EmptyResult> {
const context = this.#browsingContextStorage.getContext(params.context);
await context.cdpTarget.browserCdpClient.sendCommand(
'BluetoothEmulation.enable',
{
state: params.state,
}
);
return {};
}

async simulatePreconnectedPeripheral(
params: Bluetooth.SimulatePreconnectedPeripheralParameters
): Promise<EmptyResult> {
const context = this.#browsingContextStorage.getContext(params.context);
await context.cdpTarget.browserCdpClient.sendCommand(
'BluetoothEmulation.simulatePreconnectedPeripheral',
{
address: params.address,
name: params.name,
knownServiceUuids: params.knownServiceUuids,
manufacturerData: params.manufacturerData,
}
);
return {};
}

async simulateAdvertisement(
params: Bluetooth.SimulateAdvertisementParameters
): Promise<EmptyResult> {
const context = this.#browsingContextStorage.getContext(params.context);
await context.cdpTarget.browserCdpClient.sendCommand(
'BluetoothEmulation.simulateAdvertisement',
{
entry: params.scanEntry,
}
);
return {};
}

onCdpTargetCreated(cdpTarget: CdpTarget) {
cdpTarget.cdpClient.on('DeviceAccess.deviceRequestPrompted', (event) => {
this.#eventManager.registerEvent(
Expand Down
15 changes: 15 additions & 0 deletions src/protocol/chromium-bidi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,21 @@ export type Command = (
// not re-define it. Therefore, it's not part of generated types.
id: WebDriverBidi.JsUint;
} & WebDriverBidiBluetooth.Bluetooth.HandleRequestDevicePrompt)
| ({
// id is defined by the main WebDriver BiDi spec and extension specs do
// not re-define it. Therefore, it's not part of generated types.
id: WebDriverBidi.JsUint;
} & WebDriverBidiBluetooth.Bluetooth.SimulateAdapter)
| ({
// id is defined by the main WebDriver BiDi spec and extension specs do
// not re-define it. Therefore, it's not part of generated types.
id: WebDriverBidi.JsUint;
} & WebDriverBidiBluetooth.Bluetooth.SimulatePreconnectedPeripheral)
| ({
// id is defined by the main WebDriver BiDi spec and extension specs do
// not re-define it. Therefore, it's not part of generated types.
id: WebDriverBidi.JsUint;
} & WebDriverBidiBluetooth.Bluetooth.SimulateAdvertisement)
) & {
channel?: WebDriverBidi.Script.Channel;
};
Expand Down
157 changes: 157 additions & 0 deletions tests/bluetooth/test_emulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# Copyright 2024 Google LLC.
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
from test_helpers import (AnyExtending, execute_command, goto_url,
send_JSON_command, subscribe, wait_for_event)

HTML_SINGLE_PERIPHERAL = """
<div>
<button id="bluetooth">bluetooth</button>
<script>
const options = {filters: [{name:"SomeDevice"}]};
document.getElementById('bluetooth').addEventListener('click', () => {
navigator.bluetooth.requestDevice(options);
});
</script>
</div>
"""

# Create a fake BT device.
fake_device_address = '09:09:09:09:09:09'


async def setup_device(websocket, context_id):
# Simulate a Bluetooth adapter.
await execute_command(
websocket, {
'method': 'bluetooth.simulateAdapter',
'params': {
'context': context_id,
'state': 'powered-on',
}
})

# Create a fake BT device.
fake_device_address = '09:09:09:09:09:09'
await execute_command(
websocket, {
'method': 'bluetooth.simulatePreconnectedPeripheral',
'params': {
'context': context_id,
'address': fake_device_address,
'name': 'SomeDevice',
'manufacturerData': [{
'key': 17,
'data': 'AP8BAX8=',
}],
'knownServiceUuids':
['12345678-1234-5678-9abc-def123456789', ],
}
})


@pytest.mark.asyncio
@pytest.mark.parametrize('capabilities', [{
'goog:chromeOptions': {
'args': ['--enable-features=WebBluetooth']
}
}],
indirect=True)
async def test_bluetooth_requestDevicePromptUpdated(websocket, context_id,
html, test_headless_mode):
if test_headless_mode == "old":
pytest.xfail("Old headless mode does not support Bluetooth")

await subscribe(websocket, ['bluetooth'])

url = html(HTML_SINGLE_PERIPHERAL)
await goto_url(websocket, context_id, url)

await setup_device(websocket, context_id)

await send_JSON_command(
websocket, {
'method': 'script.evaluate',
'params': {
'expression': 'document.querySelector("#bluetooth").click();',
'awaitPromise': True,
'target': {
'context': context_id,
},
'userActivation': True
}
})

response = await wait_for_event(websocket,
'bluetooth.requestDevicePromptUpdated')
assert response == AnyExtending({
'type': 'event',
'method': 'bluetooth.requestDevicePromptUpdated',
'params': {
'context': context_id,
'devices': [{
'id': fake_device_address
}],
}
})


@pytest.mark.asyncio
@pytest.mark.parametrize('capabilities', [{
'goog:chromeOptions': {
'args': ['--enable-features=WebBluetooth']
}
}],
indirect=True)
@pytest.mark.parametrize('accept', [True, False])
async def test_bluetooth_handleRequestDevicePrompt(websocket, context_id, html,
test_headless_mode, accept):
if test_headless_mode == "old":
pytest.xfail("Old headless mode does not support Bluetooth")

await subscribe(websocket, ['bluetooth'])

url = html(HTML_SINGLE_PERIPHERAL)
await goto_url(websocket, context_id, url)

await setup_device(websocket, context_id)

await send_JSON_command(
websocket, {
'method': 'script.evaluate',
'params': {
'expression': 'document.querySelector("#bluetooth").click();',
'awaitPromise': True,
'target': {
'context': context_id,
},
'userActivation': True
}
})

event = await wait_for_event(websocket,
'bluetooth.requestDevicePromptUpdated')

await execute_command(
websocket, {
'method': 'bluetooth.handleRequestDevicePrompt',
'params': {
'context': context_id,
'accept': accept,
'prompt': event['params']['prompt'],
'device': event['params']['devices'][0]['id']
}
})

0 comments on commit 48a233f

Please sign in to comment.