1# Copyright 2024 NXP
2#
3# SPDX-License-Identifier: Apache-2.0
4import re
5
6import pytest
7from test_l2cap_common import L2CAP_SERVER_PSM, logger
8from twister_harness import DeviceAdapter, Shell
9
10
11def pytest_addoption(parser) -> None:
12    """Add local parser options to pytest."""
13    parser.addoption('--hci-transport', default=None, help='Configuration HCI transport for bumble')
14
15
16@pytest.fixture(name='initialize', scope='session')
17def fixture_initialize(request, shell: Shell, dut: DeviceAdapter):
18    """Session initializtion"""
19    # Get HCI transport for bumble
20    hci = request.config.getoption('--hci-transport')
21
22    if hci is None:
23        for fixture in dut.device_config.fixtures:
24            if fixture.startswith('usb_hci:'):
25                hci = fixture.split(sep=':', maxsplit=1)[1]
26                break
27
28    assert hci is not None
29
30    shell.exec_command("bt init")
31    lines = dut.readlines_until("Bluetooth initialized")
32    regex = r'Identity: *(?P<bd_addr>([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}) *\((.*?)\))'
33    bd_addr = None
34    for line in lines:
35        logger.info(f"Shell log {line}")
36        m = re.search(regex, line)
37        if m:
38            bd_addr = m.group('bd_addr')
39
40    if bd_addr is None:
41        logger.error('Fail to get IUT BD address')
42        raise AssertionError
43
44    shell.exec_command("br pscan on")
45    shell.exec_command("br iscan on")
46    logger.info('initialized')
47
48    shell.exec_command(f"l2cap_br register {format(L2CAP_SERVER_PSM, 'x')}")
49    logger.info("l2cap server register")
50    return hci, bd_addr
51
52
53@pytest.fixture
54def l2cap_br_dut(initialize):
55    logger.info('Start running testcase')
56    yield initialize
57    logger.info('Done')
58