Skip to content

Firmware

Bases: DualDeviceTestBase

Test Class for Bluetooth Quality Report (BQR) tests.

This class provides tests that verify the BQR feature of the device.

Attributes:

Name Type Description
_bqr_version tuple[int, int]

The BQR version supported by the device.

_manufacturer_name str

The manufacturer name of the Bluetooth Firmware.

Source code in navi/tests/firmware/bqr_test.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
class BqrTest(test_base.DualDeviceTestBase):
  """Test Class for Bluetooth Quality Report (BQR) tests.

  This class provides tests that verify the BQR feature of the device.

  Attributes:
    _bqr_version: The BQR version supported by the device.
    _manufacturer_name: The manufacturer name of the Bluetooth Firmware.
  """

  _bqr_version: tuple[int, int] = (0, 0)
  _manufacturer_name: str = 'Unknown'

  @override
  async def async_setup_class(self) -> None:
    await super().async_setup_class()
    await self._get_firmware_manufacturer_name()
    await self._device_bqr_version_verify()

  async def _get_firmware_manufacturer_name(self) -> None:
    """get the manufacturer name."""
    if self._manufacturer_name != 'Unknown':
      return

    response = await self.dut.device.send_sync_command(
        hci.HCI_Read_Local_Version_Information_Command()
    )

    self.logger.info('send_firmware_version_info_command:')
    self.logger.info('status: %s', response.status)
    self.logger.info(
        'company_identifier: %s',
        response.company_identifier,
    )

    self._manufacturer_name = company_ids.COMPANY_IDENTIFIERS.get(
        response.company_identifier, 'Unknown'
    )

    self.logger.info('manufacturer_name: %s', self._manufacturer_name)

  async def _device_bqr_version_verify(self) -> None:
    """Verifies the BQR version of the device."""
    self.logger.info('_device_bqr_version_verify')
    response = await self.dut.device.send_sync_command(
        bqr.HciBqrLeGetVendorCapabilitiesCommand()
    )

    self._bqr_version = response.version_supported
    self.logger.info(
        '_device_bqr_version_verify _bqr_version: %s',
        self._bqr_version,
    )

  @navi_test_base.named_parameterized(
      quality_monitoring_mode_one_time_query=dict(
          bqr_eventmask=bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE,
          expected_report_id=bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE,
          bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
          bqr_minimum_report_interval=0,
          event_received_times=1,
          connection_required=True,
          min_bqr_version=bqr.Version.V1,
      ),
      quality_monitoring_mode_periodically=dict(
          bqr_eventmask=bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE,
          expected_report_id=bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE,
          bqr_report_action=bqr.BqrReportAction.ADD,
          bqr_minimum_report_interval=1000,
          event_received_times=5,
          connection_required=True,
          min_bqr_version=bqr.Version.V1,
      ),
      energy_monitoring_mode_one_time_query=dict(
          bqr_eventmask=bqr.BqrQualityEventMask.ENERGY_MONITORING_MODE,
          expected_report_id=bqr.QualityReportId.ENERGY_MONITORING_EVENT,
          bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
          bqr_minimum_report_interval=0,
          event_received_times=1,
          connection_required=True,
          min_bqr_version=bqr.Version.V3,
      ),
      energy_monitoring_mode_periodically=dict(
          bqr_eventmask=bqr.BqrQualityEventMask.ENERGY_MONITORING_MODE,
          expected_report_id=bqr.QualityReportId.ENERGY_MONITORING_EVENT,
          bqr_report_action=bqr.BqrReportAction.ADD,
          bqr_minimum_report_interval=1000,
          event_received_times=5,
          connection_required=True,
          min_bqr_version=bqr.Version.V3,
      ),
      advance_rf_status_one_time_query=dict(
          bqr_eventmask=bqr.BqrQualityEventMask.ADV_RF_STATS_TRIGGER,
          expected_report_id=bqr.QualityReportId.ADV_RF_STATUS_BY_TRIGGER,
          bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
          bqr_minimum_report_interval=0,
          event_received_times=1,
          connection_required=True,
          min_bqr_version=bqr.Version.V7,
      ),
      # TODO: The test case is blocked due to the AOSP HAL hijack
      # ADV_RF_STATUS_BY_MONITOR Vendor event.
      # advance_rf_status_periodically=dict(
      #     bqr_eventmask=bqr.BqrQualityEventMask.ADV_RF_STATS_PERIODIC,
      #     expected_report_id=bqr.QualityReportId.ADV_RF_STATUS_BY_MONITOR,
      #     bqr_report_action=bqr.BqrReportAction.ADD,
      #     bqr_minimum_report_interval=1000,
      #     event_received_times=5,
      #     connection_required=True,
      #     min_bqr_version=bqr.Version.V6,
      # ),
  )
  async def test_receive(
      self,
      bqr_eventmask: int,
      expected_report_id: bqr.QualityReportId,
      bqr_report_action: bqr.BqrReportAction,
      bqr_minimum_report_interval: int,
      event_received_times: int,
      connection_required: bool,
      min_bqr_version: bqr.Version = bqr.Version.V1,
  ) -> None:
    """Tests the BQR function.

    Args:
      bqr_eventmask: The bitmask specifying which standard quality events should
        trigger a report.
      expected_report_id: The specific BQR QualityReportId to look for.
      bqr_report_action: The BQR reporting action.
      bqr_minimum_report_interval: The minimum time interval between consecutive
        quality reports.
      event_received_times: The number of expected vendor events received.
      connection_required: The flag to verify the connection before sending the
        command.
      min_bqr_version: The minimum BQR version supported by the device.
    """

    if self._bqr_version < bqr.min_supported_vendor_version(min_bqr_version):
      self.skipTest(
          f'BQR {min_bqr_version.name}+ is not supported on this device.'
      )
    if connection_required:
      await self.create_connection(
          self.dut.device, self.ref.device, core.BT_BR_EDR_TRANSPORT
      )

    pending_event_queue = asyncio.Queue[bqr.BluetoothQualityReportEvent]()

    def on_bqr_event(event: bqr.BluetoothQualityReportEvent):
      if event.quality_report_id == expected_report_id:
        pending_event_queue.put_nowait(event)

    setattr(
        self.dut.device.host,
        f'on_{bqr.BluetoothQualityReportEvent.subclasses[expected_report_id].name.lower()}',
        on_bqr_event,
    )

    self.logger.info('Send BQR command...')
    await self.dut.device.send_sync_command(
        bqr.HciBqrBluetoothQualityReportCommand(
            bqr_report_action=bqr_report_action,
            bqr_quality_event_mask=bqr_eventmask,
            bqr_minimum_report_interval=bqr_minimum_report_interval,
            bqr_vendor_specific_quality_event_mask=0,
            bqr_vendor_specific_trace_mask=0,
            report_interval_multiple=0,
        ),
    )

    # --- Wait for Bluetooth Quality Report Vendor Event ---
    self.logger.info(
        'Waiting for BQR vendor event (ID: %r)...', expected_report_id
    )
    timeout_message = (
        f'Waiting for vendor event (ID: {expected_report_id.name})'
        f' {event_received_times} times within the'
        f' {_DEFAULT_TIMEOUT}-seconds.'
    )
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT, timeout_message):
      # Wait for an item to appear in the queue inside the context manager
      for i in range(event_received_times):
        await pending_event_queue.get()
        # This code runs only if the await completed within the timeout
        self.logger.info(
            'Received matching vendor event %d times via queue.', i + 1
        )

  async def test_device_bqr_delete_command_function(self) -> None:
    """Tests the BQR function of Delete Command.

    Test steps:
      1. Send BQR command with quality monitoring mode.
      2. Received Command Complete event and verify the status.
      3. Send BQR command with delete quality monitoring mode.
      4. Received Command Complete event and verify no more quality monitoring
      mode related vendor event.
    """
    if self._bqr_version < bqr.min_supported_vendor_version(bqr.Version.V1):
      self.skipTest('BQR v1+ is not supported on this device.')

    bqr_eventmask = bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE
    expected_report_id = (
        bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE
    )
    bqr_report_action = bqr.BqrReportAction.ADD  # Periodically
    bqr_minimum_report_interval = 1000  # 1000 ms
    event_received_times = 5  # 5 times events should be received
    await self.test_receive(
        bqr_eventmask,
        expected_report_id,
        bqr_report_action,
        bqr_minimum_report_interval,
        event_received_times,
        connection_required=True,
        min_bqr_version=bqr.Version.V1,
    )

    # Delete the BQR reporting mode and verify the status.
    pending_event_queue = asyncio.Queue[hci.HCI_Event]()

    await self.dut.device.send_sync_command(
        bqr.HciBqrBluetoothQualityReportCommand(
            bqr_report_action=bqr.BqrReportAction.DELETE,  # Delete Command
            bqr_quality_event_mask=bqr_eventmask,
            bqr_minimum_report_interval=0,
            bqr_vendor_specific_quality_event_mask=0,
            bqr_vendor_specific_trace_mask=0,
            report_interval_multiple=0,
        ),
    )

    def on_bqr_event(event: bqr.BluetoothQualityReportEvent):
      if event.quality_report_id == expected_report_id:
        pending_event_queue.put_nowait(event)

    setattr(
        self.dut.device.host,
        f'on_{bqr.BluetoothQualityReportEvent.subclasses[expected_report_id].name.lower()}',
        on_bqr_event,
    )

    # --- Verify that Bluetooth Quality Report Vendor Event Deleted ---
    self.logger.info(
        'Verify for BQR vendor event after delete command (ID: %r)...',
        expected_report_id,
    )
    async with self.assert_timeout(
        _DEFAULT_TIMEOUT, 'Received unexpected vendor event', with_log=False
    ):
      # Wait for an item to appear in the queue inside the context manager
      event = await pending_event_queue.get()
      self.logger.info('Received vendor event: %s', event)

Tests the BQR function of Delete Command.

Test steps
  1. Send BQR command with quality monitoring mode.
  2. Received Command Complete event and verify the status.
  3. Send BQR command with delete quality monitoring mode.
  4. Received Command Complete event and verify no more quality monitoring mode related vendor event.
Source code in navi/tests/firmware/bqr_test.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
async def test_device_bqr_delete_command_function(self) -> None:
  """Tests the BQR function of Delete Command.

  Test steps:
    1. Send BQR command with quality monitoring mode.
    2. Received Command Complete event and verify the status.
    3. Send BQR command with delete quality monitoring mode.
    4. Received Command Complete event and verify no more quality monitoring
    mode related vendor event.
  """
  if self._bqr_version < bqr.min_supported_vendor_version(bqr.Version.V1):
    self.skipTest('BQR v1+ is not supported on this device.')

  bqr_eventmask = bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE
  expected_report_id = (
      bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE
  )
  bqr_report_action = bqr.BqrReportAction.ADD  # Periodically
  bqr_minimum_report_interval = 1000  # 1000 ms
  event_received_times = 5  # 5 times events should be received
  await self.test_receive(
      bqr_eventmask,
      expected_report_id,
      bqr_report_action,
      bqr_minimum_report_interval,
      event_received_times,
      connection_required=True,
      min_bqr_version=bqr.Version.V1,
  )

  # Delete the BQR reporting mode and verify the status.
  pending_event_queue = asyncio.Queue[hci.HCI_Event]()

  await self.dut.device.send_sync_command(
      bqr.HciBqrBluetoothQualityReportCommand(
          bqr_report_action=bqr.BqrReportAction.DELETE,  # Delete Command
          bqr_quality_event_mask=bqr_eventmask,
          bqr_minimum_report_interval=0,
          bqr_vendor_specific_quality_event_mask=0,
          bqr_vendor_specific_trace_mask=0,
          report_interval_multiple=0,
      ),
  )

  def on_bqr_event(event: bqr.BluetoothQualityReportEvent):
    if event.quality_report_id == expected_report_id:
      pending_event_queue.put_nowait(event)

  setattr(
      self.dut.device.host,
      f'on_{bqr.BluetoothQualityReportEvent.subclasses[expected_report_id].name.lower()}',
      on_bqr_event,
  )

  # --- Verify that Bluetooth Quality Report Vendor Event Deleted ---
  self.logger.info(
      'Verify for BQR vendor event after delete command (ID: %r)...',
      expected_report_id,
  )
  async with self.assert_timeout(
      _DEFAULT_TIMEOUT, 'Received unexpected vendor event', with_log=False
  ):
    # Wait for an item to appear in the queue inside the context manager
    event = await pending_event_queue.get()
    self.logger.info('Received vendor event: %s', event)

Tests the BQR function.

Parameters:

Name Type Description Default
bqr_eventmask int

The bitmask specifying which standard quality events should trigger a report.

required
expected_report_id QualityReportId

The specific BQR QualityReportId to look for.

required
bqr_report_action BqrReportAction

The BQR reporting action.

required
bqr_minimum_report_interval int

The minimum time interval between consecutive quality reports.

required
event_received_times int

The number of expected vendor events received.

required
connection_required bool

The flag to verify the connection before sending the command.

required
min_bqr_version Version

The minimum BQR version supported by the device.

V1
Source code in navi/tests/firmware/bqr_test.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@navi_test_base.named_parameterized(
    quality_monitoring_mode_one_time_query=dict(
        bqr_eventmask=bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE,
        expected_report_id=bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE,
        bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
        bqr_minimum_report_interval=0,
        event_received_times=1,
        connection_required=True,
        min_bqr_version=bqr.Version.V1,
    ),
    quality_monitoring_mode_periodically=dict(
        bqr_eventmask=bqr.BqrQualityEventMask.QUALITY_MONITORING_MODE,
        expected_report_id=bqr.QualityReportId.QUALITY_REPORTING_ON_THE_MONITORING_MODE,
        bqr_report_action=bqr.BqrReportAction.ADD,
        bqr_minimum_report_interval=1000,
        event_received_times=5,
        connection_required=True,
        min_bqr_version=bqr.Version.V1,
    ),
    energy_monitoring_mode_one_time_query=dict(
        bqr_eventmask=bqr.BqrQualityEventMask.ENERGY_MONITORING_MODE,
        expected_report_id=bqr.QualityReportId.ENERGY_MONITORING_EVENT,
        bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
        bqr_minimum_report_interval=0,
        event_received_times=1,
        connection_required=True,
        min_bqr_version=bqr.Version.V3,
    ),
    energy_monitoring_mode_periodically=dict(
        bqr_eventmask=bqr.BqrQualityEventMask.ENERGY_MONITORING_MODE,
        expected_report_id=bqr.QualityReportId.ENERGY_MONITORING_EVENT,
        bqr_report_action=bqr.BqrReportAction.ADD,
        bqr_minimum_report_interval=1000,
        event_received_times=5,
        connection_required=True,
        min_bqr_version=bqr.Version.V3,
    ),
    advance_rf_status_one_time_query=dict(
        bqr_eventmask=bqr.BqrQualityEventMask.ADV_RF_STATS_TRIGGER,
        expected_report_id=bqr.QualityReportId.ADV_RF_STATUS_BY_TRIGGER,
        bqr_report_action=bqr.BqrReportAction.ONE_TIME_QUERY,
        bqr_minimum_report_interval=0,
        event_received_times=1,
        connection_required=True,
        min_bqr_version=bqr.Version.V7,
    ),
    # TODO: The test case is blocked due to the AOSP HAL hijack
    # ADV_RF_STATUS_BY_MONITOR Vendor event.
    # advance_rf_status_periodically=dict(
    #     bqr_eventmask=bqr.BqrQualityEventMask.ADV_RF_STATS_PERIODIC,
    #     expected_report_id=bqr.QualityReportId.ADV_RF_STATUS_BY_MONITOR,
    #     bqr_report_action=bqr.BqrReportAction.ADD,
    #     bqr_minimum_report_interval=1000,
    #     event_received_times=5,
    #     connection_required=True,
    #     min_bqr_version=bqr.Version.V6,
    # ),
)
async def test_receive(
    self,
    bqr_eventmask: int,
    expected_report_id: bqr.QualityReportId,
    bqr_report_action: bqr.BqrReportAction,
    bqr_minimum_report_interval: int,
    event_received_times: int,
    connection_required: bool,
    min_bqr_version: bqr.Version = bqr.Version.V1,
) -> None:
  """Tests the BQR function.

  Args:
    bqr_eventmask: The bitmask specifying which standard quality events should
      trigger a report.
    expected_report_id: The specific BQR QualityReportId to look for.
    bqr_report_action: The BQR reporting action.
    bqr_minimum_report_interval: The minimum time interval between consecutive
      quality reports.
    event_received_times: The number of expected vendor events received.
    connection_required: The flag to verify the connection before sending the
      command.
    min_bqr_version: The minimum BQR version supported by the device.
  """

  if self._bqr_version < bqr.min_supported_vendor_version(min_bqr_version):
    self.skipTest(
        f'BQR {min_bqr_version.name}+ is not supported on this device.'
    )
  if connection_required:
    await self.create_connection(
        self.dut.device, self.ref.device, core.BT_BR_EDR_TRANSPORT
    )

  pending_event_queue = asyncio.Queue[bqr.BluetoothQualityReportEvent]()

  def on_bqr_event(event: bqr.BluetoothQualityReportEvent):
    if event.quality_report_id == expected_report_id:
      pending_event_queue.put_nowait(event)

  setattr(
      self.dut.device.host,
      f'on_{bqr.BluetoothQualityReportEvent.subclasses[expected_report_id].name.lower()}',
      on_bqr_event,
  )

  self.logger.info('Send BQR command...')
  await self.dut.device.send_sync_command(
      bqr.HciBqrBluetoothQualityReportCommand(
          bqr_report_action=bqr_report_action,
          bqr_quality_event_mask=bqr_eventmask,
          bqr_minimum_report_interval=bqr_minimum_report_interval,
          bqr_vendor_specific_quality_event_mask=0,
          bqr_vendor_specific_trace_mask=0,
          report_interval_multiple=0,
      ),
  )

  # --- Wait for Bluetooth Quality Report Vendor Event ---
  self.logger.info(
      'Waiting for BQR vendor event (ID: %r)...', expected_report_id
  )
  timeout_message = (
      f'Waiting for vendor event (ID: {expected_report_id.name})'
      f' {event_received_times} times within the'
      f' {_DEFAULT_TIMEOUT}-seconds.'
  )
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT, timeout_message):
    # Wait for an item to appear in the queue inside the context manager
    for i in range(event_received_times):
      await pending_event_queue.get()
      # This code runs only if the await completed within the timeout
      self.logger.info(
          'Received matching vendor event %d times via queue.', i + 1
      )

Bases: DualDeviceTestBase

Source code in navi/tests/firmware/channel_sounding_test.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
class ChannelSoundingTest(test_base.DualDeviceTestBase):

  @override
  async def async_setup_class(self) -> None:
    await super().async_setup_class()
    if not self.dut.device.supports_le_features(
        hci.LeFeatureMask.CHANNEL_SOUNDING
    ):
      raise signals.TestAbortClass('Channel Sounding is not supported on DUT')
    if not self.ref.device.supports_le_features(
        hci.LeFeatureMask.CHANNEL_SOUNDING
    ):
      raise signals.TestAbortClass('Channel Sounding is not supported on REF')
    self.dut.config.channel_sounding_enabled = True
    self.ref.config.channel_sounding_enabled = True

  @navi_test_base.named_parameterized(
      initiate=constants.Direction.INCOMING,
      reflect=constants.Direction.OUTGOING,
  )
  async def test_mode_2(self, direction: constants.Direction) -> None:
    """Test Channel Sounding from DUT."""
    if direction == constants.Direction.INCOMING:
      central, peripheral = self.ref, self.dut
      central_tag = 'REF'
      peripheral_tag = 'DUT'
    else:
      central, peripheral = self.dut, self.ref
      central_tag = 'DUT'
      peripheral_tag = 'REF'

    connections = await self.create_connection(
        central=central.device,
        peripheral=peripheral.device,
        link_type=core.PhysicalTransport.LE,
    )
    await self.encrypt_connection(connections)

    subevent_results = [
        asyncio.Queue[hci.HCI_LE_CS_Subevent_Result_Event]() for _ in range(2)
    ]
    central.device.host.on('cs_subevent_result', subevent_results[0].put_nowait)
    peripheral.device.host.on(
        'cs_subevent_result', subevent_results[1].put_nowait
    )
    if not (central_cs_capabilities := central.device.cs_capabilities):
      self.fail(f'{central_tag} does not support Channel Sounding.')

    self.logger.info('Setup Channel Sounding')
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('[%s] Set default CS settings', central_tag)
      await central.device.set_default_cs_settings(connections[0])
      self.logger.info('[%s] Set default CS settings', peripheral_tag)
      await peripheral.device.set_default_cs_settings(connections[1])

      # Wait for CS settings to be ready.
      await asyncio.sleep(1)

      self.logger.info('[%s] Get remote CS capabilities', central_tag)
      peripheral_cs_capabilities = (
          await central.device.get_remote_cs_capabilities(connections[0])
      )

      self.logger.info('[%s] Create CS config', central_tag)
      config = await central.device.create_cs_config(
          connections[0], main_mode_type=0x02
      )
      self.logger.info('[%s] Enable CS security', central_tag)
      await central.device.enable_cs_security(connections[0])
      tone_antenna_config_selection = _CS_TONE_ANTENNA_CONFIG_MAPPING_TABLE[
          central_cs_capabilities.num_antennas_supported - 1
      ][peripheral_cs_capabilities.num_antennas_supported - 1]
      self.logger.info('[%s] Set CS procedure parameters', central_tag)
      await central.device.set_cs_procedure_parameters(
          connection=connections[0],
          config=config,
          tone_antenna_config_selection=tone_antenna_config_selection,
          preferred_peer_antenna=_CS_PREFERRED_PEER_ANTENNA_MAPPING_TABLE[
              tone_antenna_config_selection
          ],
      )

      self.logger.info('[%s] Enable CS Procedure', central_tag)
      await central.device.enable_cs_procedure(
          connection=connections[0], config=config
      )
      self.logger.info('[%s] Wait for Subevent Result', central_tag)
      await subevent_results[0].get()
      self.logger.info('[%s] Wait for Subevent Result', peripheral_tag)
      await subevent_results[1].get()

Test Channel Sounding from DUT.

Source code in navi/tests/firmware/channel_sounding_test.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@navi_test_base.named_parameterized(
    initiate=constants.Direction.INCOMING,
    reflect=constants.Direction.OUTGOING,
)
async def test_mode_2(self, direction: constants.Direction) -> None:
  """Test Channel Sounding from DUT."""
  if direction == constants.Direction.INCOMING:
    central, peripheral = self.ref, self.dut
    central_tag = 'REF'
    peripheral_tag = 'DUT'
  else:
    central, peripheral = self.dut, self.ref
    central_tag = 'DUT'
    peripheral_tag = 'REF'

  connections = await self.create_connection(
      central=central.device,
      peripheral=peripheral.device,
      link_type=core.PhysicalTransport.LE,
  )
  await self.encrypt_connection(connections)

  subevent_results = [
      asyncio.Queue[hci.HCI_LE_CS_Subevent_Result_Event]() for _ in range(2)
  ]
  central.device.host.on('cs_subevent_result', subevent_results[0].put_nowait)
  peripheral.device.host.on(
      'cs_subevent_result', subevent_results[1].put_nowait
  )
  if not (central_cs_capabilities := central.device.cs_capabilities):
    self.fail(f'{central_tag} does not support Channel Sounding.')

  self.logger.info('Setup Channel Sounding')
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('[%s] Set default CS settings', central_tag)
    await central.device.set_default_cs_settings(connections[0])
    self.logger.info('[%s] Set default CS settings', peripheral_tag)
    await peripheral.device.set_default_cs_settings(connections[1])

    # Wait for CS settings to be ready.
    await asyncio.sleep(1)

    self.logger.info('[%s] Get remote CS capabilities', central_tag)
    peripheral_cs_capabilities = (
        await central.device.get_remote_cs_capabilities(connections[0])
    )

    self.logger.info('[%s] Create CS config', central_tag)
    config = await central.device.create_cs_config(
        connections[0], main_mode_type=0x02
    )
    self.logger.info('[%s] Enable CS security', central_tag)
    await central.device.enable_cs_security(connections[0])
    tone_antenna_config_selection = _CS_TONE_ANTENNA_CONFIG_MAPPING_TABLE[
        central_cs_capabilities.num_antennas_supported - 1
    ][peripheral_cs_capabilities.num_antennas_supported - 1]
    self.logger.info('[%s] Set CS procedure parameters', central_tag)
    await central.device.set_cs_procedure_parameters(
        connection=connections[0],
        config=config,
        tone_antenna_config_selection=tone_antenna_config_selection,
        preferred_peer_antenna=_CS_PREFERRED_PEER_ANTENNA_MAPPING_TABLE[
            tone_antenna_config_selection
        ],
    )

    self.logger.info('[%s] Enable CS Procedure', central_tag)
    await central.device.enable_cs_procedure(
        connection=connections[0], config=config
    )
    self.logger.info('[%s] Wait for Subevent Result', central_tag)
    await subevent_results[0].get()
    self.logger.info('[%s] Wait for Subevent Result', peripheral_tag)
    await subevent_results[1].get()

Bases: DualDeviceTestBase

Tests for Classic connection.

Source code in navi/tests/firmware/classic_test.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
class ClassicTest(test_base.DualDeviceTestBase):
  """Tests for Classic connection."""

  @override
  async def async_setup_class(self) -> None:
    await super().async_setup_class()
    self.is_emulator = (
        isinstance(self.dut.adapter, crown.AndroidCrownAdapter)
        and self.dut.adapter.ad.is_emulator
    )
    response = await self.dut.device.send_sync_command(
        hci.HCI_Read_Local_Supported_Codecs_Command()
    )
    self.dut_supported_codecs = set(response.standard_codec_ids)
    response = await self.ref.device.send_sync_command(
        hci.HCI_Read_Local_Supported_Codecs_Command()
    )
    self.ref_supported_codecs = set(response.standard_codec_ids)

    self.logger.info('dut_supported_codecs: %s', self.dut_supported_codecs)
    self.logger.info('ref_supported_codecs: %s', self.ref_supported_codecs)

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_connect(
      self, direction: constants.Direction
  ) -> tuple[device_lib.Connection, device_lib.Connection]:
    """Tests connecting to a remote device."""

    if direction == constants.Direction.OUTGOING:
      central, peripheral = self.dut.device, self.ref.device
    else:
      central, peripheral = self.ref.device, self.dut.device
    return await self.create_connection(
        central,
        peripheral,
        core.PhysicalTransport.BR_EDR,
    )

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_inquiry(self, direction: constants.Direction) -> None:
    """Tests inquiry."""

    if direction == constants.Direction.OUTGOING:
      central, peripheral = self.dut.device, self.ref.device
    else:
      central, peripheral = self.ref.device, self.dut.device

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('[Peripheral] Set discoverable.')
      await peripheral.set_discoverable(True)
      self.logger.info('[Central] Look for discoverable devices.')
      device_found = asyncio.Event()

      @central.on(central.EVENT_INQUIRY_RESULT)
      def on_inquiry_result(
          address: hci.Address,
          class_of_device: int,
          data: device_lib.AdvertisingData,
          rssi: int,
      ) -> None:
        del class_of_device, data, rssi
        if address == peripheral.public_address:
          device_found.set()

      self.logger.info('[Central] Start discovery.')
      await central.start_discovery()
      self.logger.info('[Central] Waiting for device found.')
      await device_found.wait()

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_remote_name_request(
      self, direction: constants.Direction
  ) -> None:
    """Tests remote name request."""

    if direction == constants.Direction.OUTGOING:
      central, peripheral = self.dut.device, self.ref.device
    else:
      central, peripheral = self.ref.device, self.dut.device

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      name = await central.request_remote_name(peripheral.public_address)
      self.assertEqual(name, peripheral.name)

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_get_remote_features(
      self, direction: constants.Direction
  ) -> None:
    """Tests get remote features."""

    connections = await self.test_connect(direction)

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('[Central] Get remote features.')
      await connections[0].get_remote_classic_features()
      self.logger.info('[Peripheral] Get remote features.')
      await connections[1].get_remote_classic_features()

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_authentication(
      self, direction: constants.Direction
  ) -> tuple[device_lib.Connection, device_lib.Connection]:
    """Tests authentication."""
    connections = await self.test_connect(direction)

    # Inject pairing keys to the devices.
    pairing_keys = keys.PairingKeys()
    pairing_keys.link_key = keys.PairingKeys.Key(
        secrets.token_bytes(16), authenticated=True
    )

    for connection in connections:
      await connection.device.update_keys(
          str(connection.peer_address), pairing_keys
      )
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('Authenticating connection.')
      await connections[0].authenticate()

    return connections

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_encryption(self, direction: constants.Direction) -> None:
    """Tests encryption."""
    connections = await self.test_authentication(direction)

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      encryption_results: list[asyncio.Future[None]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, encryption_result in zip(connections, encryption_results):
        connection.once(
            connection.EVENT_CONNECTION_ENCRYPTION_CHANGE,
            functools.partial(encryption_result.set_result, None),
        )
        connection.once(
            connection.EVENT_CONNECTION_ENCRYPTION_FAILURE,
            functools.partial(
                lambda result, reason: result.set_exception(
                    hci.HCI_Error(reason)
                ),
                encryption_result,
            ),
        )
      self.logger.info('Encrypting connection.')
      await connections[0].encrypt()

      self.logger.info('Waiting for encryption results.')
      await asyncio.gather(*encryption_results)

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_switch_role(self, direction: constants.Direction) -> None:
    """Tests switch role."""

    self.logger.info('Allow role switch.')
    for device in self._devices:
      await device.device.send_sync_command(
          hci.HCI_Write_Default_Link_Policy_Settings_Command(
              default_link_policy_settings=0x01
          )
      )

    connections = await self.create_connection(
        self.dut.device,
        self.ref.device,
        core.PhysicalTransport.BR_EDR,
    )

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      role_change_results: list[asyncio.Future[hci.Role]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, role_change_result in zip(
          connections, role_change_results
      ):
        connection.once(
            connection.EVENT_ROLE_CHANGE, role_change_result.set_result
        )
        connection.once(
            connection.EVENT_ROLE_CHANGE_FAILURE,
            functools.partial(
                lambda result, reason: result.set_exception(
                    hci.HCI_Error(reason)
                ),
                role_change_result,
            ),
        )

      if direction == constants.Direction.OUTGOING:
        self.logger.info('Switching role to peripheral.')
        await connections[0].switch_role(hci.Role.PERIPHERAL)
      else:  # direction == constants.Direction.INCOMING
        self.logger.info('Switching role to central.')
        await connections[1].switch_role(hci.Role.CENTRAL)

      self.logger.info('Waiting for role change results.')
      await asyncio.gather(*role_change_results)

  async def test_send_acl_data(self) -> None:
    """Tests switch role."""
    connections = await self.create_connection(
        self.dut.device,
        self.ref.device,
        core.PhysicalTransport.BR_EDR,
    )

    cid = 33
    data_size = 4096
    sample_data = bytes([i % 256 for i in range(data_size)])

    sinks = [asyncio.Queue[bytes]() for _ in range(2)]
    connections[0].device.l2cap_channel_manager.register_fixed_channel(
        cid, lambda _, data: sinks[0].put_nowait(data)
    )
    connections[1].device.l2cap_channel_manager.register_fixed_channel(
        cid, lambda _, data: sinks[1].put_nowait(data)
    )

    self.logger.info('Enqueuing ACL data.')
    connections[0].send_l2cap_pdu(cid, sample_data)
    connections[1].send_l2cap_pdu(cid, sample_data)
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('Waiting for ACL data received.')
      received_datas = (bytearray(), bytearray())
      while len(received_datas[0]) < data_size:
        received_datas[0].extend(await sinks[0].get())
      while len(received_datas[1]) < data_size:
        received_datas[1].extend(await sinks[1].get())
      self.assertEqual(received_datas[0], sample_data)
      self.assertEqual(received_datas[1], sample_data)

  @navi_test_base.parameterized(
      *itertools.product(constants.Direction, _SNIFF_MODE_PARAMS)
  )
  async def test_sniff_mode(
      self, direction: constants.Direction, sniff_mode_param: SniffModeParams
  ) -> None:
    """Tests sniff mode."""
    if self.is_emulator:
      self.skipTest('Sniff mode is not supported by Rootcanal.')
    # Enable sniff mode on both devices.
    for device in self._devices:
      await device.device.send_sync_command(
          hci.HCI_Write_Default_Link_Policy_Settings_Command(
              default_link_policy_settings=1 << 2,
          )
      )

    connections = await self.test_connect(direction)

    def register_mode_change_callbacks(
        connections: list[device_lib.Connection],
    ) -> list[asyncio.Future[None]]:
      mode_change_results: list[asyncio.Future[None]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, mode_change_result in zip(
          connections, mode_change_results
      ):
        connection.once(
            connection.EVENT_MODE_CHANGE,
            functools.partial(mode_change_result.set_result, None),
        )
        connection.once(
            connection.EVENT_MODE_CHANGE_FAILURE,
            mode_change_result.set_result,
        )
      return mode_change_results

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      mode_change_results = register_mode_change_callbacks(connections)
      self.logger.info('Entering sniff mode.')
      await connections[0].device.send_async_command(
          hci.HCI_Sniff_Mode_Command(
              connection_handle=connections[0].handle,
              sniff_max_interval=sniff_mode_param.max_interval,
              sniff_min_interval=sniff_mode_param.min_interval,
              sniff_attempt=sniff_mode_param.sniff_attempt,
              sniff_timeout=sniff_mode_param.sniff_timeout,
          )
      )

      self.logger.info('Waiting for mode change results.')
      self.assertSequenceEqual(
          await asyncio.gather(*mode_change_results),
          [None, None],
          msg='Failed to enter sniff mode.',
      )

      for connection in connections:
        self.assertEqual(
            connection.classic_mode,
            hci.HCI_Mode_Change_Event.Mode.SNIFF,
            msg='Connection is not in sniff mode.',
        )
        self.assertGreaterEqual(
            connection.classic_interval,
            sniff_mode_param.min_interval,
            msg='Connection mode interval is less than min interval.',
        )
        self.assertLessEqual(
            connection.classic_interval,
            sniff_mode_param.max_interval,
            msg='Connection mode interval is greater than max interval.',
        )

      mode_change_results = register_mode_change_callbacks(connections)

      self.logger.info('Exiting sniff mode.')
      await connections[0].device.send_async_command(
          hci.HCI_Exit_Sniff_Mode_Command(
              connection_handle=connections[0].handle,
          )
      )
      self.logger.info('Waiting for mode change results.')
      self.assertSequenceEqual(
          await asyncio.gather(*mode_change_results),
          [None, None],
          msg='Failed to exit sniff mode.',
      )

      for connection in connections:
        self.assertEqual(
            connection.classic_mode,
            hci.HCI_Mode_Change_Event.Mode.ACTIVE,
            msg='Connection is not in active mode.',
        )

  @navi_test_base.named_parameterized(
      incoming_cvsd_s4=dict(
          direction=constants.Direction.INCOMING,
          sco_parameters=hfp.ESCO_PARAMETERS[
              hfp.DefaultCodecParameters.ESCO_CVSD_S4
          ],
      ),
      outgoing_cvsd_s4=dict(
          direction=constants.Direction.OUTGOING,
          sco_parameters=hfp.ESCO_PARAMETERS[
              hfp.DefaultCodecParameters.ESCO_CVSD_S4
          ],
      ),
      incoming_transparent_t2=dict(
          direction=constants.Direction.INCOMING,
          sco_parameters=hfp_ext.ESCO_PARAMETERS_T2_TRANSPARENT,
      ),
      outgoing_transparent_t2=dict(
          direction=constants.Direction.OUTGOING,
          sco_parameters=hfp_ext.ESCO_PARAMETERS_T2_TRANSPARENT,
      ),
      incoming_msbc_t2=dict(
          direction=constants.Direction.INCOMING,
          sco_parameters=hfp.ESCO_PARAMETERS[
              hfp.DefaultCodecParameters.ESCO_MSBC_T2
          ],
      ),
      outgoing_msbc_t2=dict(
          direction=constants.Direction.OUTGOING,
          sco_parameters=hfp.ESCO_PARAMETERS[
              hfp.DefaultCodecParameters.ESCO_MSBC_T2
          ],
      ),
      incoming_lc3_t2=dict(
          direction=constants.Direction.INCOMING,
          sco_parameters=hfp_ext.ESCO_PARAMETERS_LC3_T2,
      ),
      outgoing_lc3_t2=dict(
          direction=constants.Direction.OUTGOING,
          sco_parameters=hfp_ext.ESCO_PARAMETERS_LC3_T2,
      ),
  )
  async def test_esco_connection(
      self, direction: constants.Direction, sco_parameters: hfp.EscoParameters
  ) -> None:
    """Tests legacy pairing."""
    codec_id = sco_parameters.transmit_coding_format.codec_id
    if not self.is_emulator:
      if codec_id not in self.dut_supported_codecs:
        self.skipTest(f'Codec {codec_id} is not supported by DUT.')
      if codec_id not in self.ref_supported_codecs:
        self.skipTest(f'Codec {codec_id} is not supported by REF.')

    connections = await self.test_connect(direction)

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      sco_connection_results: list[asyncio.Future[device_lib.ScoLink]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, sco_connection_result in zip(
          connections, sco_connection_results
      ):
        connection.device.once(
            connection.device.EVENT_SCO_CONNECTION,
            sco_connection_result.set_result,
        )
        # EVENT_SCO_CONNECTION_FAILURE doesn't provide status code.
        connection.device.once(
            connection.device.EVENT_SCO_CONNECTION_FAILURE,
            functools.partial(
                sco_connection_result.set_exception,
                AssertionError('SCO connection failed.'),
            ),
        )

      sco_requests = asyncio.Queue[int]()
      connections[1].device.on(
          connections[1].device.EVENT_SCO_REQUEST,
          lambda connection, link_type: sco_requests.put_nowait(link_type),
      )

      self.logger.info('[Central] Establishing SCO connection.')
      await connections[0].device.send_async_command(
          hci.HCI_Enhanced_Setup_Synchronous_Connection_Command(
              connection_handle=connections[0].handle,
              **sco_parameters.asdict(),
          )
      )

      self.logger.info('[Peripheral] Waiting for SCO request.')
      link_type = await sco_requests.get()

      self.assertEqual(
          link_type,
          hci.HCI_Connection_Complete_Event.LinkType.ESCO,
          msg='SCO link type is not ESCO.',
      )

      self.logger.info('[Peripheral] Accepting SCO request.')
      await connections[1].device.send_async_command(
          hci.HCI_Enhanced_Accept_Synchronous_Connection_Request_Command(
              bd_addr=connections[1].peer_address,
              **sco_parameters.asdict(),
          )
      )

      self.logger.info('Waiting for SCO connection results.')
      sco_connections = await asyncio.gather(*sco_connection_results)

      disconnection_results: list[asyncio.Future[int]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for sco_connection, disconnection_result in zip(
          sco_connections, disconnection_results
      ):
        sco_connection.once(
            sco_connection.EVENT_DISCONNECTION,
            disconnection_result.set_result,
        )

      self.logger.info('[Central] Disconnecting SCO connection.')
      await sco_connections[0].disconnect()

      self.logger.info('Waiting for disconnection results.')
      await asyncio.gather(*disconnection_results)

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_legacy_pairing(self, direction: constants.Direction) -> None:
    """Tests legacy pairing."""
    self.logger.info('[REF] Disable SSP.')
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.ref.device.classic_sc_enabled = False
      self.ref.device.classic_ssp_enabled = False
      await self.ref.device.power_on()

    for device in self._devices:
      device.device.pairing_config_factory = lambda _: pairing.PairingConfig(
          delegate=_LegacyPairingDelegate(
              io_capability=pairing.PairingDelegate.IoCapability.KEYBOARD_INPUT_ONLY,
              pin='123456',
          )
      )
    connections = await self.test_connect(direction)

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      link_key_results: list[asyncio.Future[None]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, link_key_result in zip(connections, link_key_results):
        connection.once(
            connection.EVENT_LINK_KEY,
            functools.partial(link_key_result.set_result, None),
        )

      self.logger.info('Authenticating connection.')
      await connections[0].authenticate()

      self.logger.info('Waiting for link key notifications.')
      await asyncio.gather(*link_key_results)

    self.assertEqual(
        await self.dut.device.get_link_key(self.ref.device.public_address),
        await self.ref.device.get_link_key(self.dut.device.public_address),
        msg='Link keys are not the same.',
    )

  @navi_test_base.parameterized(*[
      (variant, direction, io_capability)
      for variant, direction, io_capability in itertools.product(
          TestVariant,
          constants.Direction,
          [
              _IoCapability.NO_OUTPUT_NO_INPUT,
              _IoCapability.KEYBOARD_INPUT_ONLY,
              _IoCapability.DISPLAY_OUTPUT_ONLY,
              _IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT,
          ],
      )
      if not (
          # PASSKEY_NOTIFICATION cannot be rejected.
          variant == TestVariant.REJECT
          and io_capability == _IoCapability.KEYBOARD_INPUT_ONLY
      )
  ])
  async def test_ssp(
      self,
      variant: TestVariant,
      pairing_direction: constants.Direction,
      ref_io_capability: _IoCapability,
  ) -> None:
    """Tests Simple Secure Pairing.

    Test steps:
      1. Setup configurations.
      2. Make ACL connections.
      3. Start pairing.
      4. Wait for pairing requests and verify pins.
      5. Make actions corresponding to variants.
      6. Verify final states.

    Args:
      variant: Action to perform in the pairing procedure.
      pairing_direction: Direction of pairing. DUT->REF is outgoing, and vice
        versa.
      ref_io_capability: IO Capability on the REF device.
    """
    self.logger.info('Enable SSP.')
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      for device in self._devices:
        device.device.classic_sc_enabled = True
        device.device.classic_ssp_enabled = True
        await device.device.power_on()

    # Android almost always uses DISPLAY_OUTPUT_AND_YES_NO_INPUT.
    dut_pairing_delegate = pairing_utils.PairingDelegate(
        io_capability=_IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT,
        auto_accept=True,
    )
    ref_pairing_delegate = pairing_utils.PairingDelegate(
        io_capability=ref_io_capability,
        auto_accept=True,
    )

    def pairing_config_factory(
        connection: device_lib.Connection,
        pairing_delegate: pairing_utils.PairingDelegate,
    ) -> pairing.PairingConfig:
      del connection  # Unused.
      return pairing.PairingConfig(
          sc=True,
          mitm=True,
          bonding=True,
          identity_address_type=pairing.PairingConfig.AddressType.PUBLIC,
          delegate=pairing_delegate,
      )

    self.logger.info('[DUT] Set pairing config factory.')
    self.dut.device.pairing_config_factory = functools.partial(
        pairing_config_factory,
        pairing_delegate=dut_pairing_delegate,
    )
    self.logger.info('[REF] Set pairing config factory.')
    self.ref.device.pairing_config_factory = functools.partial(
        pairing_config_factory,
        pairing_delegate=ref_pairing_delegate,
    )

    connections = await self.test_connect(pairing_direction)

    auth_task = asyncio.create_task(connections[0].authenticate())
    dut_accept = variant != TestVariant.REJECT
    ref_accept = variant != TestVariant.REJECTED

    pairing_futures: list[asyncio.Future[int | None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    link_key_futures: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, pairing_future, link_key_future in zip(
        connections, pairing_futures, link_key_futures
    ):
      connection.once(
          connection.EVENT_CLASSIC_PAIRING,
          functools.partial(pairing_future.set_result, None),
      )
      connection.once(
          connection.EVENT_CLASSIC_PAIRING_FAILURE,
          pairing_future.set_result,
      )
      connection.once(
          connection.EVENT_LINK_KEY,
          functools.partial(link_key_future.set_result, None),
      )

    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      self.logger.info('[DUT] Wait for pairing event.')
      dut_pairing_event = await dut_pairing_delegate.pairing_events.get()
      self.logger.info('[REF] Wait for pairing event.')
      ref_pairing_event = await ref_pairing_delegate.pairing_events.get()

      match ref_io_capability:
        case _IoCapability.NO_OUTPUT_NO_INPUT:
          expected_dut_pairing_variant = _PairingVariant.JUST_WORK
          expected_ref_pairing_variant = _PairingVariant.JUST_WORK
          dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
          ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
        case _IoCapability.KEYBOARD_INPUT_ONLY:
          expected_dut_pairing_variant = (
              _PairingVariant.PASSKEY_ENTRY_NOTIFICATION
          )
          expected_ref_pairing_variant = _PairingVariant.PASSKEY_ENTRY_REQUEST
          # For SSP PASSKEY pairing, Bumble will invoke display_number, and then
          # confirm, so we need to unblock both events.
          dut_pairing_delegate.pairing_answers.put_nowait(None)

          dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
          ref_pairing_delegate.pairing_answers.put_nowait(
              dut_pairing_event.arg if ref_accept else None
          )
        case _IoCapability.DISPLAY_OUTPUT_ONLY:
          expected_dut_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
          expected_ref_pairing_variant = (
              _PairingVariant.PASSKEY_ENTRY_NOTIFICATION
          )
          self.assertEqual(
              dut_pairing_event.arg,
              ref_pairing_event.arg,
              msg='Numeric comparison values are not the same.',
          )
          # For SSP PASSKEY pairing, Bumble will invoke display_number, and then
          # confirm, so we need to unblock both events.
          ref_pairing_delegate.pairing_answers.put_nowait(None)

          dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
          ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
        case _IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT:
          expected_dut_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
          expected_ref_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
          self.assertEqual(
              dut_pairing_event.arg,
              ref_pairing_event.arg,
              msg='Numeric comparison values are not the same.',
          )
          dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
          ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
        case _:
          raise ValueError(f'Unsupported IO capability: {ref_io_capability}')
      self.assertEqual(dut_pairing_event.variant, expected_dut_pairing_variant)
      self.assertEqual(ref_pairing_event.variant, expected_ref_pairing_variant)

      if variant == TestVariant.ACCEPT:
        self.logger.info('Waiting for pairing event.')
        self.assertSequenceEqual(
            await asyncio.gather(*pairing_futures), [None, None]
        )

        self.logger.info('Waiting for authentication complete.')
        await auth_task

        self.logger.info('Waiting for link key notifications.')
        await asyncio.gather(*link_key_futures)

        self.assertEqual(
            await self.dut.device.get_link_key(self.ref.device.public_address),
            await self.ref.device.get_link_key(self.dut.device.public_address),
            msg='Link keys are not the same.',
        )
      else:
        self.logger.info('Waiting for pairing failure.')
        self.assertSequenceEqual(
            await asyncio.gather(*pairing_futures),
            [
                hci.HCI_ErrorCode.AUTHENTICATION_FAILURE_ERROR,
                hci.HCI_ErrorCode.AUTHENTICATION_FAILURE_ERROR,
            ],
        )

        self.logger.info('Waiting for authentication failure.')
        with self.assertRaises((hci.HCI_Error, asyncio.CancelledError)):
          await auth_task

Tests authentication.

Source code in navi/tests/firmware/classic_test.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_authentication(
    self, direction: constants.Direction
) -> tuple[device_lib.Connection, device_lib.Connection]:
  """Tests authentication."""
  connections = await self.test_connect(direction)

  # Inject pairing keys to the devices.
  pairing_keys = keys.PairingKeys()
  pairing_keys.link_key = keys.PairingKeys.Key(
      secrets.token_bytes(16), authenticated=True
  )

  for connection in connections:
    await connection.device.update_keys(
        str(connection.peer_address), pairing_keys
    )
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('Authenticating connection.')
    await connections[0].authenticate()

  return connections

Tests connecting to a remote device.

Source code in navi/tests/firmware/classic_test.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_connect(
    self, direction: constants.Direction
) -> tuple[device_lib.Connection, device_lib.Connection]:
  """Tests connecting to a remote device."""

  if direction == constants.Direction.OUTGOING:
    central, peripheral = self.dut.device, self.ref.device
  else:
    central, peripheral = self.ref.device, self.dut.device
  return await self.create_connection(
      central,
      peripheral,
      core.PhysicalTransport.BR_EDR,
  )

Tests encryption.

Source code in navi/tests/firmware/classic_test.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_encryption(self, direction: constants.Direction) -> None:
  """Tests encryption."""
  connections = await self.test_authentication(direction)

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    encryption_results: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, encryption_result in zip(connections, encryption_results):
      connection.once(
          connection.EVENT_CONNECTION_ENCRYPTION_CHANGE,
          functools.partial(encryption_result.set_result, None),
      )
      connection.once(
          connection.EVENT_CONNECTION_ENCRYPTION_FAILURE,
          functools.partial(
              lambda result, reason: result.set_exception(
                  hci.HCI_Error(reason)
              ),
              encryption_result,
          ),
      )
    self.logger.info('Encrypting connection.')
    await connections[0].encrypt()

    self.logger.info('Waiting for encryption results.')
    await asyncio.gather(*encryption_results)

Tests legacy pairing.

Source code in navi/tests/firmware/classic_test.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@navi_test_base.named_parameterized(
    incoming_cvsd_s4=dict(
        direction=constants.Direction.INCOMING,
        sco_parameters=hfp.ESCO_PARAMETERS[
            hfp.DefaultCodecParameters.ESCO_CVSD_S4
        ],
    ),
    outgoing_cvsd_s4=dict(
        direction=constants.Direction.OUTGOING,
        sco_parameters=hfp.ESCO_PARAMETERS[
            hfp.DefaultCodecParameters.ESCO_CVSD_S4
        ],
    ),
    incoming_transparent_t2=dict(
        direction=constants.Direction.INCOMING,
        sco_parameters=hfp_ext.ESCO_PARAMETERS_T2_TRANSPARENT,
    ),
    outgoing_transparent_t2=dict(
        direction=constants.Direction.OUTGOING,
        sco_parameters=hfp_ext.ESCO_PARAMETERS_T2_TRANSPARENT,
    ),
    incoming_msbc_t2=dict(
        direction=constants.Direction.INCOMING,
        sco_parameters=hfp.ESCO_PARAMETERS[
            hfp.DefaultCodecParameters.ESCO_MSBC_T2
        ],
    ),
    outgoing_msbc_t2=dict(
        direction=constants.Direction.OUTGOING,
        sco_parameters=hfp.ESCO_PARAMETERS[
            hfp.DefaultCodecParameters.ESCO_MSBC_T2
        ],
    ),
    incoming_lc3_t2=dict(
        direction=constants.Direction.INCOMING,
        sco_parameters=hfp_ext.ESCO_PARAMETERS_LC3_T2,
    ),
    outgoing_lc3_t2=dict(
        direction=constants.Direction.OUTGOING,
        sco_parameters=hfp_ext.ESCO_PARAMETERS_LC3_T2,
    ),
)
async def test_esco_connection(
    self, direction: constants.Direction, sco_parameters: hfp.EscoParameters
) -> None:
  """Tests legacy pairing."""
  codec_id = sco_parameters.transmit_coding_format.codec_id
  if not self.is_emulator:
    if codec_id not in self.dut_supported_codecs:
      self.skipTest(f'Codec {codec_id} is not supported by DUT.')
    if codec_id not in self.ref_supported_codecs:
      self.skipTest(f'Codec {codec_id} is not supported by REF.')

  connections = await self.test_connect(direction)

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    sco_connection_results: list[asyncio.Future[device_lib.ScoLink]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, sco_connection_result in zip(
        connections, sco_connection_results
    ):
      connection.device.once(
          connection.device.EVENT_SCO_CONNECTION,
          sco_connection_result.set_result,
      )
      # EVENT_SCO_CONNECTION_FAILURE doesn't provide status code.
      connection.device.once(
          connection.device.EVENT_SCO_CONNECTION_FAILURE,
          functools.partial(
              sco_connection_result.set_exception,
              AssertionError('SCO connection failed.'),
          ),
      )

    sco_requests = asyncio.Queue[int]()
    connections[1].device.on(
        connections[1].device.EVENT_SCO_REQUEST,
        lambda connection, link_type: sco_requests.put_nowait(link_type),
    )

    self.logger.info('[Central] Establishing SCO connection.')
    await connections[0].device.send_async_command(
        hci.HCI_Enhanced_Setup_Synchronous_Connection_Command(
            connection_handle=connections[0].handle,
            **sco_parameters.asdict(),
        )
    )

    self.logger.info('[Peripheral] Waiting for SCO request.')
    link_type = await sco_requests.get()

    self.assertEqual(
        link_type,
        hci.HCI_Connection_Complete_Event.LinkType.ESCO,
        msg='SCO link type is not ESCO.',
    )

    self.logger.info('[Peripheral] Accepting SCO request.')
    await connections[1].device.send_async_command(
        hci.HCI_Enhanced_Accept_Synchronous_Connection_Request_Command(
            bd_addr=connections[1].peer_address,
            **sco_parameters.asdict(),
        )
    )

    self.logger.info('Waiting for SCO connection results.')
    sco_connections = await asyncio.gather(*sco_connection_results)

    disconnection_results: list[asyncio.Future[int]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for sco_connection, disconnection_result in zip(
        sco_connections, disconnection_results
    ):
      sco_connection.once(
          sco_connection.EVENT_DISCONNECTION,
          disconnection_result.set_result,
      )

    self.logger.info('[Central] Disconnecting SCO connection.')
    await sco_connections[0].disconnect()

    self.logger.info('Waiting for disconnection results.')
    await asyncio.gather(*disconnection_results)

Tests get remote features.

Source code in navi/tests/firmware/classic_test.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_get_remote_features(
    self, direction: constants.Direction
) -> None:
  """Tests get remote features."""

  connections = await self.test_connect(direction)

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('[Central] Get remote features.')
    await connections[0].get_remote_classic_features()
    self.logger.info('[Peripheral] Get remote features.')
    await connections[1].get_remote_classic_features()

Tests inquiry.

Source code in navi/tests/firmware/classic_test.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_inquiry(self, direction: constants.Direction) -> None:
  """Tests inquiry."""

  if direction == constants.Direction.OUTGOING:
    central, peripheral = self.dut.device, self.ref.device
  else:
    central, peripheral = self.ref.device, self.dut.device

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('[Peripheral] Set discoverable.')
    await peripheral.set_discoverable(True)
    self.logger.info('[Central] Look for discoverable devices.')
    device_found = asyncio.Event()

    @central.on(central.EVENT_INQUIRY_RESULT)
    def on_inquiry_result(
        address: hci.Address,
        class_of_device: int,
        data: device_lib.AdvertisingData,
        rssi: int,
    ) -> None:
      del class_of_device, data, rssi
      if address == peripheral.public_address:
        device_found.set()

    self.logger.info('[Central] Start discovery.')
    await central.start_discovery()
    self.logger.info('[Central] Waiting for device found.')
    await device_found.wait()

Tests legacy pairing.

Source code in navi/tests/firmware/classic_test.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_legacy_pairing(self, direction: constants.Direction) -> None:
  """Tests legacy pairing."""
  self.logger.info('[REF] Disable SSP.')
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.ref.device.classic_sc_enabled = False
    self.ref.device.classic_ssp_enabled = False
    await self.ref.device.power_on()

  for device in self._devices:
    device.device.pairing_config_factory = lambda _: pairing.PairingConfig(
        delegate=_LegacyPairingDelegate(
            io_capability=pairing.PairingDelegate.IoCapability.KEYBOARD_INPUT_ONLY,
            pin='123456',
        )
    )
  connections = await self.test_connect(direction)

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    link_key_results: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, link_key_result in zip(connections, link_key_results):
      connection.once(
          connection.EVENT_LINK_KEY,
          functools.partial(link_key_result.set_result, None),
      )

    self.logger.info('Authenticating connection.')
    await connections[0].authenticate()

    self.logger.info('Waiting for link key notifications.')
    await asyncio.gather(*link_key_results)

  self.assertEqual(
      await self.dut.device.get_link_key(self.ref.device.public_address),
      await self.ref.device.get_link_key(self.dut.device.public_address),
      msg='Link keys are not the same.',
  )

Tests remote name request.

Source code in navi/tests/firmware/classic_test.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_remote_name_request(
    self, direction: constants.Direction
) -> None:
  """Tests remote name request."""

  if direction == constants.Direction.OUTGOING:
    central, peripheral = self.dut.device, self.ref.device
  else:
    central, peripheral = self.ref.device, self.dut.device

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    name = await central.request_remote_name(peripheral.public_address)
    self.assertEqual(name, peripheral.name)

Tests switch role.

Source code in navi/tests/firmware/classic_test.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
async def test_send_acl_data(self) -> None:
  """Tests switch role."""
  connections = await self.create_connection(
      self.dut.device,
      self.ref.device,
      core.PhysicalTransport.BR_EDR,
  )

  cid = 33
  data_size = 4096
  sample_data = bytes([i % 256 for i in range(data_size)])

  sinks = [asyncio.Queue[bytes]() for _ in range(2)]
  connections[0].device.l2cap_channel_manager.register_fixed_channel(
      cid, lambda _, data: sinks[0].put_nowait(data)
  )
  connections[1].device.l2cap_channel_manager.register_fixed_channel(
      cid, lambda _, data: sinks[1].put_nowait(data)
  )

  self.logger.info('Enqueuing ACL data.')
  connections[0].send_l2cap_pdu(cid, sample_data)
  connections[1].send_l2cap_pdu(cid, sample_data)
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('Waiting for ACL data received.')
    received_datas = (bytearray(), bytearray())
    while len(received_datas[0]) < data_size:
      received_datas[0].extend(await sinks[0].get())
    while len(received_datas[1]) < data_size:
      received_datas[1].extend(await sinks[1].get())
    self.assertEqual(received_datas[0], sample_data)
    self.assertEqual(received_datas[1], sample_data)

Tests sniff mode.

Source code in navi/tests/firmware/classic_test.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
@navi_test_base.parameterized(
    *itertools.product(constants.Direction, _SNIFF_MODE_PARAMS)
)
async def test_sniff_mode(
    self, direction: constants.Direction, sniff_mode_param: SniffModeParams
) -> None:
  """Tests sniff mode."""
  if self.is_emulator:
    self.skipTest('Sniff mode is not supported by Rootcanal.')
  # Enable sniff mode on both devices.
  for device in self._devices:
    await device.device.send_sync_command(
        hci.HCI_Write_Default_Link_Policy_Settings_Command(
            default_link_policy_settings=1 << 2,
        )
    )

  connections = await self.test_connect(direction)

  def register_mode_change_callbacks(
      connections: list[device_lib.Connection],
  ) -> list[asyncio.Future[None]]:
    mode_change_results: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, mode_change_result in zip(
        connections, mode_change_results
    ):
      connection.once(
          connection.EVENT_MODE_CHANGE,
          functools.partial(mode_change_result.set_result, None),
      )
      connection.once(
          connection.EVENT_MODE_CHANGE_FAILURE,
          mode_change_result.set_result,
      )
    return mode_change_results

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    mode_change_results = register_mode_change_callbacks(connections)
    self.logger.info('Entering sniff mode.')
    await connections[0].device.send_async_command(
        hci.HCI_Sniff_Mode_Command(
            connection_handle=connections[0].handle,
            sniff_max_interval=sniff_mode_param.max_interval,
            sniff_min_interval=sniff_mode_param.min_interval,
            sniff_attempt=sniff_mode_param.sniff_attempt,
            sniff_timeout=sniff_mode_param.sniff_timeout,
        )
    )

    self.logger.info('Waiting for mode change results.')
    self.assertSequenceEqual(
        await asyncio.gather(*mode_change_results),
        [None, None],
        msg='Failed to enter sniff mode.',
    )

    for connection in connections:
      self.assertEqual(
          connection.classic_mode,
          hci.HCI_Mode_Change_Event.Mode.SNIFF,
          msg='Connection is not in sniff mode.',
      )
      self.assertGreaterEqual(
          connection.classic_interval,
          sniff_mode_param.min_interval,
          msg='Connection mode interval is less than min interval.',
      )
      self.assertLessEqual(
          connection.classic_interval,
          sniff_mode_param.max_interval,
          msg='Connection mode interval is greater than max interval.',
      )

    mode_change_results = register_mode_change_callbacks(connections)

    self.logger.info('Exiting sniff mode.')
    await connections[0].device.send_async_command(
        hci.HCI_Exit_Sniff_Mode_Command(
            connection_handle=connections[0].handle,
        )
    )
    self.logger.info('Waiting for mode change results.')
    self.assertSequenceEqual(
        await asyncio.gather(*mode_change_results),
        [None, None],
        msg='Failed to exit sniff mode.',
    )

    for connection in connections:
      self.assertEqual(
          connection.classic_mode,
          hci.HCI_Mode_Change_Event.Mode.ACTIVE,
          msg='Connection is not in active mode.',
      )

Tests Simple Secure Pairing.

Test steps
  1. Setup configurations.
  2. Make ACL connections.
  3. Start pairing.
  4. Wait for pairing requests and verify pins.
  5. Make actions corresponding to variants.
  6. Verify final states.

Parameters:

Name Type Description Default
variant TestVariant

Action to perform in the pairing procedure.

required
pairing_direction Direction

Direction of pairing. DUT->REF is outgoing, and vice versa.

required
ref_io_capability _IoCapability

IO Capability on the REF device.

required
Source code in navi/tests/firmware/classic_test.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
@navi_test_base.parameterized(*[
    (variant, direction, io_capability)
    for variant, direction, io_capability in itertools.product(
        TestVariant,
        constants.Direction,
        [
            _IoCapability.NO_OUTPUT_NO_INPUT,
            _IoCapability.KEYBOARD_INPUT_ONLY,
            _IoCapability.DISPLAY_OUTPUT_ONLY,
            _IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT,
        ],
    )
    if not (
        # PASSKEY_NOTIFICATION cannot be rejected.
        variant == TestVariant.REJECT
        and io_capability == _IoCapability.KEYBOARD_INPUT_ONLY
    )
])
async def test_ssp(
    self,
    variant: TestVariant,
    pairing_direction: constants.Direction,
    ref_io_capability: _IoCapability,
) -> None:
  """Tests Simple Secure Pairing.

  Test steps:
    1. Setup configurations.
    2. Make ACL connections.
    3. Start pairing.
    4. Wait for pairing requests and verify pins.
    5. Make actions corresponding to variants.
    6. Verify final states.

  Args:
    variant: Action to perform in the pairing procedure.
    pairing_direction: Direction of pairing. DUT->REF is outgoing, and vice
      versa.
    ref_io_capability: IO Capability on the REF device.
  """
  self.logger.info('Enable SSP.')
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    for device in self._devices:
      device.device.classic_sc_enabled = True
      device.device.classic_ssp_enabled = True
      await device.device.power_on()

  # Android almost always uses DISPLAY_OUTPUT_AND_YES_NO_INPUT.
  dut_pairing_delegate = pairing_utils.PairingDelegate(
      io_capability=_IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT,
      auto_accept=True,
  )
  ref_pairing_delegate = pairing_utils.PairingDelegate(
      io_capability=ref_io_capability,
      auto_accept=True,
  )

  def pairing_config_factory(
      connection: device_lib.Connection,
      pairing_delegate: pairing_utils.PairingDelegate,
  ) -> pairing.PairingConfig:
    del connection  # Unused.
    return pairing.PairingConfig(
        sc=True,
        mitm=True,
        bonding=True,
        identity_address_type=pairing.PairingConfig.AddressType.PUBLIC,
        delegate=pairing_delegate,
    )

  self.logger.info('[DUT] Set pairing config factory.')
  self.dut.device.pairing_config_factory = functools.partial(
      pairing_config_factory,
      pairing_delegate=dut_pairing_delegate,
  )
  self.logger.info('[REF] Set pairing config factory.')
  self.ref.device.pairing_config_factory = functools.partial(
      pairing_config_factory,
      pairing_delegate=ref_pairing_delegate,
  )

  connections = await self.test_connect(pairing_direction)

  auth_task = asyncio.create_task(connections[0].authenticate())
  dut_accept = variant != TestVariant.REJECT
  ref_accept = variant != TestVariant.REJECTED

  pairing_futures: list[asyncio.Future[int | None]] = [
      asyncio.get_running_loop().create_future() for _ in range(2)
  ]
  link_key_futures: list[asyncio.Future[None]] = [
      asyncio.get_running_loop().create_future() for _ in range(2)
  ]
  for connection, pairing_future, link_key_future in zip(
      connections, pairing_futures, link_key_futures
  ):
    connection.once(
        connection.EVENT_CLASSIC_PAIRING,
        functools.partial(pairing_future.set_result, None),
    )
    connection.once(
        connection.EVENT_CLASSIC_PAIRING_FAILURE,
        pairing_future.set_result,
    )
    connection.once(
        connection.EVENT_LINK_KEY,
        functools.partial(link_key_future.set_result, None),
    )

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    self.logger.info('[DUT] Wait for pairing event.')
    dut_pairing_event = await dut_pairing_delegate.pairing_events.get()
    self.logger.info('[REF] Wait for pairing event.')
    ref_pairing_event = await ref_pairing_delegate.pairing_events.get()

    match ref_io_capability:
      case _IoCapability.NO_OUTPUT_NO_INPUT:
        expected_dut_pairing_variant = _PairingVariant.JUST_WORK
        expected_ref_pairing_variant = _PairingVariant.JUST_WORK
        dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
        ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
      case _IoCapability.KEYBOARD_INPUT_ONLY:
        expected_dut_pairing_variant = (
            _PairingVariant.PASSKEY_ENTRY_NOTIFICATION
        )
        expected_ref_pairing_variant = _PairingVariant.PASSKEY_ENTRY_REQUEST
        # For SSP PASSKEY pairing, Bumble will invoke display_number, and then
        # confirm, so we need to unblock both events.
        dut_pairing_delegate.pairing_answers.put_nowait(None)

        dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
        ref_pairing_delegate.pairing_answers.put_nowait(
            dut_pairing_event.arg if ref_accept else None
        )
      case _IoCapability.DISPLAY_OUTPUT_ONLY:
        expected_dut_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
        expected_ref_pairing_variant = (
            _PairingVariant.PASSKEY_ENTRY_NOTIFICATION
        )
        self.assertEqual(
            dut_pairing_event.arg,
            ref_pairing_event.arg,
            msg='Numeric comparison values are not the same.',
        )
        # For SSP PASSKEY pairing, Bumble will invoke display_number, and then
        # confirm, so we need to unblock both events.
        ref_pairing_delegate.pairing_answers.put_nowait(None)

        dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
        ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
      case _IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT:
        expected_dut_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
        expected_ref_pairing_variant = _PairingVariant.NUMERIC_COMPARISON
        self.assertEqual(
            dut_pairing_event.arg,
            ref_pairing_event.arg,
            msg='Numeric comparison values are not the same.',
        )
        dut_pairing_delegate.pairing_answers.put_nowait(dut_accept)
        ref_pairing_delegate.pairing_answers.put_nowait(ref_accept)
      case _:
        raise ValueError(f'Unsupported IO capability: {ref_io_capability}')
    self.assertEqual(dut_pairing_event.variant, expected_dut_pairing_variant)
    self.assertEqual(ref_pairing_event.variant, expected_ref_pairing_variant)

    if variant == TestVariant.ACCEPT:
      self.logger.info('Waiting for pairing event.')
      self.assertSequenceEqual(
          await asyncio.gather(*pairing_futures), [None, None]
      )

      self.logger.info('Waiting for authentication complete.')
      await auth_task

      self.logger.info('Waiting for link key notifications.')
      await asyncio.gather(*link_key_futures)

      self.assertEqual(
          await self.dut.device.get_link_key(self.ref.device.public_address),
          await self.ref.device.get_link_key(self.dut.device.public_address),
          msg='Link keys are not the same.',
      )
    else:
      self.logger.info('Waiting for pairing failure.')
      self.assertSequenceEqual(
          await asyncio.gather(*pairing_futures),
          [
              hci.HCI_ErrorCode.AUTHENTICATION_FAILURE_ERROR,
              hci.HCI_ErrorCode.AUTHENTICATION_FAILURE_ERROR,
          ],
      )

      self.logger.info('Waiting for authentication failure.')
      with self.assertRaises((hci.HCI_Error, asyncio.CancelledError)):
        await auth_task

Tests switch role.

Source code in navi/tests/firmware/classic_test.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_switch_role(self, direction: constants.Direction) -> None:
  """Tests switch role."""

  self.logger.info('Allow role switch.')
  for device in self._devices:
    await device.device.send_sync_command(
        hci.HCI_Write_Default_Link_Policy_Settings_Command(
            default_link_policy_settings=0x01
        )
    )

  connections = await self.create_connection(
      self.dut.device,
      self.ref.device,
      core.PhysicalTransport.BR_EDR,
  )

  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    role_change_results: list[asyncio.Future[hci.Role]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, role_change_result in zip(
        connections, role_change_results
    ):
      connection.once(
          connection.EVENT_ROLE_CHANGE, role_change_result.set_result
      )
      connection.once(
          connection.EVENT_ROLE_CHANGE_FAILURE,
          functools.partial(
              lambda result, reason: result.set_exception(
                  hci.HCI_Error(reason)
              ),
              role_change_result,
          ),
      )

    if direction == constants.Direction.OUTGOING:
      self.logger.info('Switching role to peripheral.')
      await connections[0].switch_role(hci.Role.PERIPHERAL)
    else:  # direction == constants.Direction.INCOMING
      self.logger.info('Switching role to central.')
      await connections[1].switch_role(hci.Role.CENTRAL)

    self.logger.info('Waiting for role change results.')
    await asyncio.gather(*role_change_results)

Bases: DualDeviceTestBase

Source code in navi/tests/firmware/le_broadcast_test.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
class LeBroadcastTest(test_base.DualDeviceTestBase):

  @override
  async def async_setup_class(self) -> None:
    await super().async_setup_class()
    if not self.dut.device.supports_le_features(
        hci.LeFeatureMask.ISOCHRONOUS_BROADCASTER
    ) or not self.ref.device.supports_le_features(
        hci.LeFeatureMask.ISOCHRONOUS_BROADCASTER
    ):
      raise signals.TestAbortClass(
          'LE Broadcast Isochronous Channels is not supported.'
      )

  async def _create_big(
      self,
      source_device: device.Device,
      broadcast_code: bytes | None = None,
  ) -> device.Big:
    """Creates a LE Broadcast Isochronous Group on the source device.

    Args:
      source_device: The source device to create the BIG on.
      broadcast_code: The broadcast code to use.

    Returns:
      The created LE Broadcast Isochronous Group.
    """
    self.logger.info('[Source] Creating advertising set.')
    advertising_set = await source_device.create_advertising_set(
        advertising_parameters=device.AdvertisingParameters(
            advertising_event_properties=device.AdvertisingEventProperties(
                is_connectable=False
            ),
            own_address_type=hci.OwnAddressType.RANDOM,
            primary_advertising_interval_min=100,
            primary_advertising_interval_max=200,
        ),
        periodic_advertising_parameters=device.PeriodicAdvertisingParameters(
            periodic_advertising_interval_min=80,
            periodic_advertising_interval_max=160,
        ),
        auto_restart=True,
        auto_start=True,
    )
    self.logger.info('[Source] Starting periodic advertising.')
    await advertising_set.start_periodic()
    self.logger.info('[Source] Creating big.')
    big = await source_device.create_big(
        advertising_set,
        parameters=device.BigParameters(
            num_bis=2,
            sdu_interval=10000,
            max_sdu=100,
            max_transport_latency=65,
            rtn=4,
            broadcast_code=broadcast_code,
        ),
    )
    return big

  @retry.retry_on_exception()
  async def _create_pa_sync(
      self, sink_device: device.Device, advertising_set: device.AdvertisingSet
  ) -> device.PeriodicAdvertisingSync:
    """Creates a LE Periodic Advertising Sync on the sink device.

    Args:
      sink_device: The sink device to create the PA Sync on.
      advertising_set: The advertising set to sync.

    Returns:
      The created LE Periodic Advertising Sync.
    """

    advertisements = asyncio.Queue[device.Advertisement]()
    sink_device.on(device.Device.EVENT_ADVERTISEMENT, advertisements.put_nowait)
    self.logger.info('[Sink] Starting scanning.')
    await sink_device.start_scanning()

    while advertisement := await advertisements.get():
      if advertisement.address == advertising_set.random_address:
        self.logger.info('[Sink] Found advertisement.')
        break

    self.logger.info('[Sink] Creating periodic advertising sync.')
    pa_sync = await sink_device.create_periodic_advertising_sync(
        advertiser_address=advertisement.address, sid=advertisement.sid
    )
    if pa_sync.state != pa_sync.State.ESTABLISHED:
      pa_sync_result = asyncio.get_running_loop().create_future()
      pa_sync.once(
          pa_sync.EVENT_ESTABLISHMENT, lambda: pa_sync_result.set_result(None)
      )
      pa_sync.once(
          pa_sync.EVENT_ESTABLISHMENT_ERROR,
          lambda: pa_sync_result.set_exception(hci.HCI_Error(pa_sync.status)),
      )
      self.logger.info('[Sink] Waiting for PA sync establishment.')
      try:
        await pa_sync_result
      finally:
        if pa_sync.state == pa_sync.State.PENDING:
          self.logger.info('[Sink] Cancel PA sync.')
          await pa_sync.terminate()
        self.logger.info('[Sink] Stopping scanning.')
        await sink_device.stop_scanning()
    return pa_sync

  async def _create_big_sync(
      self,
      sink_device: device.Device,
      big: device.Big,
      broadcast_code: bytes | None = None,
  ) -> device.BigSync:
    """Creates a LE Broadcast Isochronous Group Sync on the sink device.

    Args:
      sink_device: The sink device to create the BIG Sync on.
      big: The BIG to sync.
      broadcast_code: The broadcast code to use.

    Returns:
      The created LE Broadcast Isochronous Group Sync.
    """
    pa_sync = await self._create_pa_sync(sink_device, big.advertising_set)
    big_info_advertisements = asyncio.Queue[device.BigInfoAdvertisement]()
    pa_sync.on(
        pa_sync.EVENT_BIGINFO_ADVERTISEMENT,
        big_info_advertisements.put_nowait,
    )
    self.logger.info('[Sink] Wait for big info advertisement.')
    await big_info_advertisements.get()

    self.logger.info('[Sink] Creating big sync.')
    big_sync = await sink_device.create_big_sync(
        pa_sync,
        device.BigSyncParameters(
            big_sync_timeout=0x4000, bis=[1, 2], broadcast_code=broadcast_code
        ),
    )
    await sink_device.stop_scanning()
    return big_sync

  async def _big_transfer(
      self,
      source_to_sink: device.Connection,
      sink_to_source: device.Connection,
      adv_set: device.AdvertisingSet,
  ) -> device.BigInfoAdvertisement:
    transfers = asyncio.Queue[device.PeriodicAdvertisingSync]()

    @sink_to_source.device.on(
        sink_to_source.device.EVENT_PERIODIC_ADVERTISING_SYNC_TRANSFER
    )
    def _(
        transfer: device.PeriodicAdvertisingSync, connection: device.Connection
    ):
      del connection  # Unused.
      transfers.put_nowait(transfer)

    self.logger.info('[Source] Transferring periodic info.')
    await adv_set.transfer_periodic_info(source_to_sink)
    self.logger.info('[Sink] Waiting for transfer.')
    pa_sync = await transfers.get()
    big_info_advertisements = asyncio.Queue[device.BigInfoAdvertisement]()
    pa_sync.on(
        pa_sync.EVENT_BIGINFO_ADVERTISEMENT,
        big_info_advertisements.put_nowait,
    )
    self.logger.info('[Sink] Waiting for big info advertisement.')
    big_info_advertisement = await big_info_advertisements.get()
    return big_info_advertisement

  @navi_test_base.named_parameterized(
      unencrypted=dict(broadcast_code=None),
      encrypted=dict(broadcast_code=_BROADCAST_CODE),
  )
  async def test_create_big(self, broadcast_code: bytes | None) -> None:
    """Test creating Broadcast Isochronous Group on DUT.

    Test steps:
      1. Create a LE Big on DUT.
      2. Create a LE Big Sync on REF.

    Args:
      broadcast_code: The broadcast code to use.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      big = await self._create_big(
          self.dut.device, broadcast_code=broadcast_code
      )
      await self._create_big_sync(
          self.ref.device, big, broadcast_code=broadcast_code
      )

  @navi_test_base.named_parameterized(
      unencrypted=dict(broadcast_code=None),
      encrypted=dict(broadcast_code=_BROADCAST_CODE),
  )
  async def test_create_big_sync(self, broadcast_code: bytes | None) -> None:
    """Test creating Big Sync on DUT.

    Test steps:
      1. Create a LE Big on REF.
      2. Create a LE Big Sync on DUT.

    Args:
      broadcast_code: The broadcast code to use.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      big = await self._create_big(
          self.ref.device, broadcast_code=broadcast_code
      )
      await self._create_big_sync(
          self.dut.device, big, broadcast_code=broadcast_code
      )

  async def test_terminate_big(self) -> None:
    """Test terminating Big on DUT.

    Test steps:
      1. Create a LE Big on REF.
      2. Create a LE Big Sync on DUT.
      3. Terminate the LE Big on DUT.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      big = await self._create_big(self.dut.device, broadcast_code=None)
      self.logger.info('[DUT] Terminating big.')
      await big.terminate()

  async def test_big_sync_terminate(self) -> None:
    """Test terminating Big Sync on DUT.

    Test steps:
      1. Create a LE Big on REF.
      2. Create a LE Big Sync on DUT.
      3. Terminate the LE Big on DUT.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      big = await self._create_big(self.ref.device)
      big_sync = await self._create_big_sync(self.dut.device, big)
      self.logger.info('[DUT] Terminating big sync.')
      # TODO: Use big_sync.terminate() once the bug is fixed.
      await self.dut.device.send_command(
          hci.HCI_LE_BIG_Terminate_Sync_Command(big_handle=big_sync.big_handle),
          check_result=True,
      )

  async def test_big_sync_lost(self) -> None:
    """Test Big Sync lost due to source termination.

    Test steps:
      1. Create a LE Big on REF.
      2. Create a LE Big Sync on DUT.
      3. Terminate the LE Big on REF.
      4. Verify that the LE Big Sync is terminated on DUT.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      big = await self._create_big(self.ref.device)
      big_sync = await self._create_big_sync(self.dut.device, big)
      big_sync_terminations = asyncio.Queue[int]()
      big_sync.on(big_sync.Event.TERMINATION, big_sync_terminations.put_nowait)
      self.logger.info('[REF] Terminating big.')
      await big.terminate()
      self.logger.info('[DUT] Waiting for big sync termination.')
      await big_sync_terminations.get()

  @navi_test_base.named_parameterized(
      outgoing=dict(is_outgoing=True),
      incoming=dict(is_outgoing=False),
  )
  async def test_transfer(self, is_outgoing: bool) -> None:
    """Test transferring Periodic Advertising Sync.

    Test steps:
      1. Create a LE Big.
      2. Create a LE Big Sync.
      3. Transfer the LE Big.
      4. Verify that the LE Big Sync is transferred.

    Args:
      is_outgoing: True if the transfer is outgoing, False if it is incoming.
    """
    async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
      sink_device = self.dut.device if is_outgoing else self.ref.device
      source_device = self.ref.device if is_outgoing else self.dut.device
      await sink_device.send_command(
          hci.HCI_LE_Set_Default_Periodic_Advertising_Sync_Transfer_Parameters_Command(
              mode=0x02,  # PA Report enabled, duplicate non-filtered.
              skip=0x00,
              sync_timeout=0x4000,
              cte_type=0x00,  # No CTE type limitation,
          ),
          check_result=True,
      )
      big = await self._create_big(source_device)
      source_to_sink, sink_to_source = await self.create_connection(
          central=source_device,
          peripheral=sink_device,
          link_type=core.BT_LE_TRANSPORT,
      )
      await self._big_transfer(
          source_to_sink, sink_to_source, big.advertising_set
      )

Test Big Sync lost due to source termination.

Test steps
  1. Create a LE Big on REF.
  2. Create a LE Big Sync on DUT.
  3. Terminate the LE Big on REF.
  4. Verify that the LE Big Sync is terminated on DUT.
Source code in navi/tests/firmware/le_broadcast_test.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
async def test_big_sync_lost(self) -> None:
  """Test Big Sync lost due to source termination.

  Test steps:
    1. Create a LE Big on REF.
    2. Create a LE Big Sync on DUT.
    3. Terminate the LE Big on REF.
    4. Verify that the LE Big Sync is terminated on DUT.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    big = await self._create_big(self.ref.device)
    big_sync = await self._create_big_sync(self.dut.device, big)
    big_sync_terminations = asyncio.Queue[int]()
    big_sync.on(big_sync.Event.TERMINATION, big_sync_terminations.put_nowait)
    self.logger.info('[REF] Terminating big.')
    await big.terminate()
    self.logger.info('[DUT] Waiting for big sync termination.')
    await big_sync_terminations.get()

Test terminating Big Sync on DUT.

Test steps
  1. Create a LE Big on REF.
  2. Create a LE Big Sync on DUT.
  3. Terminate the LE Big on DUT.
Source code in navi/tests/firmware/le_broadcast_test.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
async def test_big_sync_terminate(self) -> None:
  """Test terminating Big Sync on DUT.

  Test steps:
    1. Create a LE Big on REF.
    2. Create a LE Big Sync on DUT.
    3. Terminate the LE Big on DUT.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    big = await self._create_big(self.ref.device)
    big_sync = await self._create_big_sync(self.dut.device, big)
    self.logger.info('[DUT] Terminating big sync.')
    # TODO: Use big_sync.terminate() once the bug is fixed.
    await self.dut.device.send_command(
        hci.HCI_LE_BIG_Terminate_Sync_Command(big_handle=big_sync.big_handle),
        check_result=True,
    )

Test creating Broadcast Isochronous Group on DUT.

Test steps
  1. Create a LE Big on DUT.
  2. Create a LE Big Sync on REF.

Parameters:

Name Type Description Default
broadcast_code bytes | None

The broadcast code to use.

required
Source code in navi/tests/firmware/le_broadcast_test.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@navi_test_base.named_parameterized(
    unencrypted=dict(broadcast_code=None),
    encrypted=dict(broadcast_code=_BROADCAST_CODE),
)
async def test_create_big(self, broadcast_code: bytes | None) -> None:
  """Test creating Broadcast Isochronous Group on DUT.

  Test steps:
    1. Create a LE Big on DUT.
    2. Create a LE Big Sync on REF.

  Args:
    broadcast_code: The broadcast code to use.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    big = await self._create_big(
        self.dut.device, broadcast_code=broadcast_code
    )
    await self._create_big_sync(
        self.ref.device, big, broadcast_code=broadcast_code
    )

Test creating Big Sync on DUT.

Test steps
  1. Create a LE Big on REF.
  2. Create a LE Big Sync on DUT.

Parameters:

Name Type Description Default
broadcast_code bytes | None

The broadcast code to use.

required
Source code in navi/tests/firmware/le_broadcast_test.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@navi_test_base.named_parameterized(
    unencrypted=dict(broadcast_code=None),
    encrypted=dict(broadcast_code=_BROADCAST_CODE),
)
async def test_create_big_sync(self, broadcast_code: bytes | None) -> None:
  """Test creating Big Sync on DUT.

  Test steps:
    1. Create a LE Big on REF.
    2. Create a LE Big Sync on DUT.

  Args:
    broadcast_code: The broadcast code to use.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    big = await self._create_big(
        self.ref.device, broadcast_code=broadcast_code
    )
    await self._create_big_sync(
        self.dut.device, big, broadcast_code=broadcast_code
    )

Test terminating Big on DUT.

Test steps
  1. Create a LE Big on REF.
  2. Create a LE Big Sync on DUT.
  3. Terminate the LE Big on DUT.
Source code in navi/tests/firmware/le_broadcast_test.py
252
253
254
255
256
257
258
259
260
261
262
263
async def test_terminate_big(self) -> None:
  """Test terminating Big on DUT.

  Test steps:
    1. Create a LE Big on REF.
    2. Create a LE Big Sync on DUT.
    3. Terminate the LE Big on DUT.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    big = await self._create_big(self.dut.device, broadcast_code=None)
    self.logger.info('[DUT] Terminating big.')
    await big.terminate()

Test transferring Periodic Advertising Sync.

Test steps
  1. Create a LE Big.
  2. Create a LE Big Sync.
  3. Transfer the LE Big.
  4. Verify that the LE Big Sync is transferred.

Parameters:

Name Type Description Default
is_outgoing bool

True if the transfer is outgoing, False if it is incoming.

required
Source code in navi/tests/firmware/le_broadcast_test.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
@navi_test_base.named_parameterized(
    outgoing=dict(is_outgoing=True),
    incoming=dict(is_outgoing=False),
)
async def test_transfer(self, is_outgoing: bool) -> None:
  """Test transferring Periodic Advertising Sync.

  Test steps:
    1. Create a LE Big.
    2. Create a LE Big Sync.
    3. Transfer the LE Big.
    4. Verify that the LE Big Sync is transferred.

  Args:
    is_outgoing: True if the transfer is outgoing, False if it is incoming.
  """
  async with self.assert_not_timeout(_DEFAULT_TIMEOUT_SECONDS):
    sink_device = self.dut.device if is_outgoing else self.ref.device
    source_device = self.ref.device if is_outgoing else self.dut.device
    await sink_device.send_command(
        hci.HCI_LE_Set_Default_Periodic_Advertising_Sync_Transfer_Parameters_Command(
            mode=0x02,  # PA Report enabled, duplicate non-filtered.
            skip=0x00,
            sync_timeout=0x4000,
            cte_type=0x00,  # No CTE type limitation,
        ),
        check_result=True,
    )
    big = await self._create_big(source_device)
    source_to_sink, sink_to_source = await self.create_connection(
        central=source_device,
        peripheral=sink_device,
        link_type=core.BT_LE_TRANSPORT,
    )
    await self._big_transfer(
        source_to_sink, sink_to_source, big.advertising_set
    )

Bases: DualDeviceTestBase

Tests for LE connection.

Source code in navi/tests/firmware/le_connection_test.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
class LeConnectionTest(test_base.DualDeviceTestBase):
  """Tests for LE connection."""

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_connect(
      self, direction: constants.Direction
  ) -> tuple[device_lib.Connection, device_lib.Connection]:
    """Tests connecting to a remote device."""
    self.logger.info('Create Bluetooth LE connection.')

    if direction == constants.Direction.INCOMING:
      central, peripheral = self.ref.device, self.dut.device
    else:
      central, peripheral = self.dut.device, self.ref.device
    return await self.create_connection(
        central,
        peripheral,
        core.PhysicalTransport.LE,
    )

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_get_remote_features(
      self, direction: constants.Direction
  ) -> None:
    """Tests getting remote features.

    Test steps:
      1. Create a Bluetooth LE connection.
      2. Get remote features from the devices.

    Args:
      direction: The direction of the connection.
    """
    connections = await self.test_connect(direction)

    async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
      self.logger.info('[Central] Get remote features.')
      await connections[0].get_remote_le_features()
      self.logger.info('[Peripheral] Get remote features.')
      await connections[1].get_remote_le_features()

  @navi_test_base.parameterized(
      constants.Direction.INCOMING, constants.Direction.OUTGOING
  )
  async def test_set_phy(self, direction: constants.Direction) -> None:
    """Tests setting phy.

    Test steps:
      1. Create a Bluetooth LE connection.
      2. Set phy to tx: LE_2M, rx: LE_2M.
      3. Set phy to tx: LE_1M, rx: LE_1M.
      4. Set phy to tx: LE_CODED, rx: LE_CODED.
      3. Verify that the connection is not dropped.

    Args:
      direction: The direction of the connection.
    """
    connections = await self.test_connect(direction)

    for phy in [hci.Phy.LE_2M, hci.Phy.LE_1M, hci.Phy.LE_CODED]:
      async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
        phy_results: list[asyncio.Future[core.ConnectionPHY]] = [
            asyncio.get_running_loop().create_future() for _ in range(2)
        ]
        for connection, phy_result in zip(connections, phy_results):
          connection.once(
              connection.EVENT_CONNECTION_PHY_UPDATE, phy_result.set_result
          )
          connection.once(
              connection.EVENT_CONNECTION_PHY_UPDATE_FAILURE,
              functools.partial(
                  lambda result, reason: result.set_exception(
                      hci.HCI_Error(reason)
                  ),
                  phy_result,
              ),
          )
        self.logger.info('Setting phy to tx: %s, rx: %s', phy, phy)
        await connections[0].set_phy(tx_phys=[phy], rx_phys=[phy])

        updated_phys = await asyncio.gather(*phy_results)
        self.logger.info('Updated phys: %s', updated_phys)

        self.assertEqual(updated_phys[0].tx_phy, phy)
        self.assertEqual(updated_phys[0].rx_phy, phy)

  async def test_update_le_connection(self) -> None:
    """Tests updating LE connection parameters during transmission.

    Test steps:
      1. Create a Bluetooth LE connection.
      2. Send l2cap data packet to the devices.
      3. Update the LE connection parameters.
      4. Verify that the connection is not dropped.
    """
    self.logger.info('Create Bluetooth LE connection.')
    connection_parameters_preferences = {
        hci.Phy.LE_1M: device_lib.ConnectionParametersPreferences(
            connection_interval_min=24 * 1.25,
            connection_interval_max=40 * 1.25,
            max_latency=0,
            supervision_timeout=500 * 10,
        )
    }
    connections = await self.create_connection(
        self.dut.device,
        self.ref.device,
        core.PhysicalTransport.LE,
        connection_parameters=connection_parameters_preferences,
    )

    disconnection = asyncio.Queue[int]()
    for connection in connections:
      connection.on(connection.EVENT_DISCONNECTION, disconnection.put_nowait)

    connections[0].send_l2cap_pdu(0, bytes(50_000))
    connections[1].send_l2cap_pdu(0, bytes(50_000))

    async with self.assert_not_timeout(
        _DEFAULT_UPDATE_CONNECTION_TIMEOUT_SECONDS
    ):
      parameter_update_results: list[asyncio.Future[None]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, parameter_update_result in zip(
          connections, parameter_update_results
      ):
        connection.once(
            connection.EVENT_CONNECTION_PARAMETERS_UPDATE,
            functools.partial(parameter_update_result.set_result, None),
        )
        connection.once(
            connection.EVENT_CONNECTION_PARAMETERS_UPDATE_FAILURE,
            functools.partial(
                lambda result, reason: result.set_exception(
                    hci.HCI_Error(reason)
                ),
                parameter_update_result,
            ),
        )

      self.logger.info('Updating connection parameters.')
      await connections[0].update_parameters(
          connection_interval_min=8,
          connection_interval_max=16,
          max_latency=0,
          supervision_timeout=500,
      )

      self.logger.info('Waiting for parameter update results.')
      await asyncio.gather(*parameter_update_results)

    # Wait for 10 seconds, or until the disconnections are received.
    async with self.assert_timeout(
        _DEFAULT_CONNECTION_TIMEOUT_SECONDS,
        msg='Keep connection for 10 seconds.',
    ):
      await disconnection.get()

  async def test_encrypt_le_connection(self) -> None:
    """Tests stability by encrypting LE connection during transmission.

    Test steps:
      1. Create a Bluetooth LE connection.
      2. Inject pairing keys to the devices.
      3. Send l2cap data packet to the devices.
      4. Encrypt the LE connection.
      5. Verify that the connection is not dropped.
    """
    self.logger.info('Create Bluetooth LE connection.')
    connections = await self.create_connection(
        self.dut.device,
        self.ref.device,
        core.PhysicalTransport.LE,
    )

    # Inject pairing keys to the devices.
    pairing_keys = keys.PairingKeys()
    pairing_keys.ltk = keys.PairingKeys.Key(
        secrets.token_bytes(16), authenticated=True
    )
    await self.dut.device.update_keys(
        str(connections[0].peer_address), pairing_keys
    )
    await self.ref.device.update_keys(
        str(connections[1].peer_address), pairing_keys
    )

    disconnection = asyncio.Queue[int]()
    for connection in connections:
      connection.on(connection.EVENT_DISCONNECTION, disconnection.put_nowait)

    connections[0].send_l2cap_pdu(0, bytes(50_000))
    connections[1].send_l2cap_pdu(0, bytes(50_000))

    async with self.assert_not_timeout(
        _DEFAULT_UPDATE_CONNECTION_TIMEOUT_SECONDS
    ):
      encryption_results: list[asyncio.Future[None]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, encryption_result in zip(connections, encryption_results):
        connection.once(
            connection.EVENT_CONNECTION_ENCRYPTION_CHANGE,
            functools.partial(encryption_result.set_result, None),
        )
        connection.once(
            connection.EVENT_CONNECTION_ENCRYPTION_FAILURE,
            functools.partial(
                lambda result, reason: result.set_exception(
                    hci.HCI_Error(reason)
                ),
                encryption_result,
            ),
        )
      self.logger.info('Encrypting connection.')
      await connections[0].encrypt()

      self.logger.info('Waiting for encryption results.')
      await asyncio.gather(*encryption_results)

    # Wait for 10 seconds, or until the disconnections are received.
    async with self.assert_timeout(
        _DEFAULT_CONNECTION_TIMEOUT_SECONDS,
        msg='Keep connection for 10 seconds.',
    ):
      await disconnection.get()

  @navi_test_base.named_parameterized(*[
      dict(
          testcase_name=f'{direction.name}_{cig_parameters_name}'.lower(),
          direction=direction,
          cig_parameters=cig_parameters,
      )
      for direction, (cig_parameters_name, cig_parameters) in itertools.product(
          constants.Direction,
          _CIG_PARAMETERS.items(),
      )
  ])
  async def test_create_cis(
      self,
      direction: constants.Direction,
      cig_parameters: device_lib.CigParameters,
  ) -> None:
    """Tests creating CIS."""
    if direction == constants.Direction.OUTGOING:
      if not self.dut.device.supports_le_features(
          hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_CENTRAL
      ):
        self.skipTest('CIS central is not supported on DUT.')
      if not self.ref.device.supports_le_features(
          hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL
      ):
        self.skipTest('CIS peripheral is not supported on REF.')
    else:
      if not self.dut.device.supports_le_features(
          hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL
      ):
        self.skipTest('CIS peripheral is not supported on DUT.')
      if not self.ref.device.supports_le_features(
          hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_CENTRAL
      ):
        self.skipTest('CIS central is not supported on REF.')
      # TODO: Remove once the flag is rolled out to our emulator
      # image.
      if (
          isinstance(self.dut.adapter, crown.AndroidCrownAdapter)
          and self.dut.adapter.ad.is_emulator
      ):
        self.skipTest('Emulator Bluetooth HAL does not support CIS peripheral.')

    # Enable Connected Isochronous Stream.
    async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
      for device in self._devices:
        await device.device.send_sync_command(
            hci.HCI_LE_Set_Host_Feature_Command(
                bit_number=hci.LeFeature.CONNECTED_ISOCHRONOUS_STREAM,
                bit_value=1,
            )
        )

    self.logger.info('Create Bluetooth LE connection.')
    connections = await self.test_connect(direction)

    async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):

      self.logger.info('Setup CIS.')
      cis_handles = await connections[0].device.setup_cig(cig_parameters)

      # Auto accept CIS request from the central.
      connections[1].on(
          connections[1].EVENT_CIS_REQUEST,
          connections[1].device.accept_cis_request,
      )

      peripheral_cis_link_queue = asyncio.Queue[device_lib.CisLink]()
      connections[1].on(
          connections[1].EVENT_CIS_ESTABLISHMENT,
          peripheral_cis_link_queue.put_nowait,
      )

      self.logger.info('Create CIS.')
      central_cis_links = await connections[0].device.create_cis(
          [(cis_handle, connections[0]) for cis_handle in cis_handles]
      )

      self.logger.info('[Peripheral] Waiting for CIS establishment.')
      peripheral_cis_links = [
          await peripheral_cis_link_queue.get() for _ in central_cis_links
      ]

      self.logger.info('[Central] Setup data path.')
      for central_cis_link in central_cis_links:
        if central_cis_link.max_pdu_c_to_p > 0:
          await central_cis_link.setup_data_path(
              central_cis_link.Direction.HOST_TO_CONTROLLER,
          )
        if central_cis_link.max_pdu_p_to_c > 0:
          await central_cis_link.setup_data_path(
              central_cis_link.Direction.CONTROLLER_TO_HOST,
          )

      self.logger.info('[Peripheral] Setup data path.')
      for peripheral_cis_link in peripheral_cis_links:
        if peripheral_cis_link.max_pdu_c_to_p > 0:
          await peripheral_cis_link.setup_data_path(
              peripheral_cis_link.Direction.CONTROLLER_TO_HOST,
          )
        if peripheral_cis_link.max_pdu_p_to_c > 0:
          await peripheral_cis_link.setup_data_path(
              peripheral_cis_link.Direction.HOST_TO_CONTROLLER,
          )

      disconnection_results: list[asyncio.Future[int]] = [
          asyncio.get_running_loop().create_future()
          for _ in peripheral_cis_links
      ]
      for peripheral_cis_link, disconnection_result in zip(
          peripheral_cis_links, disconnection_results
      ):
        peripheral_cis_link.once(
            peripheral_cis_link.EVENT_DISCONNECTION,
            disconnection_result.set_result,
        )
        peripheral_cis_link.once(
            peripheral_cis_link.EVENT_DISCONNECTION_FAILURE,
            functools.partial(
                disconnection_result.set_exception,
                AssertionError('CIS disconnection failed.'),
            ),
        )

      self.logger.info('[Central] Disconnect CIS.')
      for central_cis_link in central_cis_links:
        await central_cis_link.disconnect()

      self.logger.info('[Peripheral] Waiting for CIS disconnection.')
      await asyncio.gather(*disconnection_results)

Tests connecting to a remote device.

Source code in navi/tests/firmware/le_connection_test.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_connect(
    self, direction: constants.Direction
) -> tuple[device_lib.Connection, device_lib.Connection]:
  """Tests connecting to a remote device."""
  self.logger.info('Create Bluetooth LE connection.')

  if direction == constants.Direction.INCOMING:
    central, peripheral = self.ref.device, self.dut.device
  else:
    central, peripheral = self.dut.device, self.ref.device
  return await self.create_connection(
      central,
      peripheral,
      core.PhysicalTransport.LE,
  )

Tests creating CIS.

Source code in navi/tests/firmware/le_connection_test.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
@navi_test_base.named_parameterized(*[
    dict(
        testcase_name=f'{direction.name}_{cig_parameters_name}'.lower(),
        direction=direction,
        cig_parameters=cig_parameters,
    )
    for direction, (cig_parameters_name, cig_parameters) in itertools.product(
        constants.Direction,
        _CIG_PARAMETERS.items(),
    )
])
async def test_create_cis(
    self,
    direction: constants.Direction,
    cig_parameters: device_lib.CigParameters,
) -> None:
  """Tests creating CIS."""
  if direction == constants.Direction.OUTGOING:
    if not self.dut.device.supports_le_features(
        hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_CENTRAL
    ):
      self.skipTest('CIS central is not supported on DUT.')
    if not self.ref.device.supports_le_features(
        hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL
    ):
      self.skipTest('CIS peripheral is not supported on REF.')
  else:
    if not self.dut.device.supports_le_features(
        hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL
    ):
      self.skipTest('CIS peripheral is not supported on DUT.')
    if not self.ref.device.supports_le_features(
        hci.LeFeatureMask.CONNECTED_ISOCHRONOUS_STREAM_CENTRAL
    ):
      self.skipTest('CIS central is not supported on REF.')
    # TODO: Remove once the flag is rolled out to our emulator
    # image.
    if (
        isinstance(self.dut.adapter, crown.AndroidCrownAdapter)
        and self.dut.adapter.ad.is_emulator
    ):
      self.skipTest('Emulator Bluetooth HAL does not support CIS peripheral.')

  # Enable Connected Isochronous Stream.
  async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
    for device in self._devices:
      await device.device.send_sync_command(
          hci.HCI_LE_Set_Host_Feature_Command(
              bit_number=hci.LeFeature.CONNECTED_ISOCHRONOUS_STREAM,
              bit_value=1,
          )
      )

  self.logger.info('Create Bluetooth LE connection.')
  connections = await self.test_connect(direction)

  async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):

    self.logger.info('Setup CIS.')
    cis_handles = await connections[0].device.setup_cig(cig_parameters)

    # Auto accept CIS request from the central.
    connections[1].on(
        connections[1].EVENT_CIS_REQUEST,
        connections[1].device.accept_cis_request,
    )

    peripheral_cis_link_queue = asyncio.Queue[device_lib.CisLink]()
    connections[1].on(
        connections[1].EVENT_CIS_ESTABLISHMENT,
        peripheral_cis_link_queue.put_nowait,
    )

    self.logger.info('Create CIS.')
    central_cis_links = await connections[0].device.create_cis(
        [(cis_handle, connections[0]) for cis_handle in cis_handles]
    )

    self.logger.info('[Peripheral] Waiting for CIS establishment.')
    peripheral_cis_links = [
        await peripheral_cis_link_queue.get() for _ in central_cis_links
    ]

    self.logger.info('[Central] Setup data path.')
    for central_cis_link in central_cis_links:
      if central_cis_link.max_pdu_c_to_p > 0:
        await central_cis_link.setup_data_path(
            central_cis_link.Direction.HOST_TO_CONTROLLER,
        )
      if central_cis_link.max_pdu_p_to_c > 0:
        await central_cis_link.setup_data_path(
            central_cis_link.Direction.CONTROLLER_TO_HOST,
        )

    self.logger.info('[Peripheral] Setup data path.')
    for peripheral_cis_link in peripheral_cis_links:
      if peripheral_cis_link.max_pdu_c_to_p > 0:
        await peripheral_cis_link.setup_data_path(
            peripheral_cis_link.Direction.CONTROLLER_TO_HOST,
        )
      if peripheral_cis_link.max_pdu_p_to_c > 0:
        await peripheral_cis_link.setup_data_path(
            peripheral_cis_link.Direction.HOST_TO_CONTROLLER,
        )

    disconnection_results: list[asyncio.Future[int]] = [
        asyncio.get_running_loop().create_future()
        for _ in peripheral_cis_links
    ]
    for peripheral_cis_link, disconnection_result in zip(
        peripheral_cis_links, disconnection_results
    ):
      peripheral_cis_link.once(
          peripheral_cis_link.EVENT_DISCONNECTION,
          disconnection_result.set_result,
      )
      peripheral_cis_link.once(
          peripheral_cis_link.EVENT_DISCONNECTION_FAILURE,
          functools.partial(
              disconnection_result.set_exception,
              AssertionError('CIS disconnection failed.'),
          ),
      )

    self.logger.info('[Central] Disconnect CIS.')
    for central_cis_link in central_cis_links:
      await central_cis_link.disconnect()

    self.logger.info('[Peripheral] Waiting for CIS disconnection.')
    await asyncio.gather(*disconnection_results)

Tests stability by encrypting LE connection during transmission.

Test steps
  1. Create a Bluetooth LE connection.
  2. Inject pairing keys to the devices.
  3. Send l2cap data packet to the devices.
  4. Encrypt the LE connection.
  5. Verify that the connection is not dropped.
Source code in navi/tests/firmware/le_connection_test.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
async def test_encrypt_le_connection(self) -> None:
  """Tests stability by encrypting LE connection during transmission.

  Test steps:
    1. Create a Bluetooth LE connection.
    2. Inject pairing keys to the devices.
    3. Send l2cap data packet to the devices.
    4. Encrypt the LE connection.
    5. Verify that the connection is not dropped.
  """
  self.logger.info('Create Bluetooth LE connection.')
  connections = await self.create_connection(
      self.dut.device,
      self.ref.device,
      core.PhysicalTransport.LE,
  )

  # Inject pairing keys to the devices.
  pairing_keys = keys.PairingKeys()
  pairing_keys.ltk = keys.PairingKeys.Key(
      secrets.token_bytes(16), authenticated=True
  )
  await self.dut.device.update_keys(
      str(connections[0].peer_address), pairing_keys
  )
  await self.ref.device.update_keys(
      str(connections[1].peer_address), pairing_keys
  )

  disconnection = asyncio.Queue[int]()
  for connection in connections:
    connection.on(connection.EVENT_DISCONNECTION, disconnection.put_nowait)

  connections[0].send_l2cap_pdu(0, bytes(50_000))
  connections[1].send_l2cap_pdu(0, bytes(50_000))

  async with self.assert_not_timeout(
      _DEFAULT_UPDATE_CONNECTION_TIMEOUT_SECONDS
  ):
    encryption_results: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, encryption_result in zip(connections, encryption_results):
      connection.once(
          connection.EVENT_CONNECTION_ENCRYPTION_CHANGE,
          functools.partial(encryption_result.set_result, None),
      )
      connection.once(
          connection.EVENT_CONNECTION_ENCRYPTION_FAILURE,
          functools.partial(
              lambda result, reason: result.set_exception(
                  hci.HCI_Error(reason)
              ),
              encryption_result,
          ),
      )
    self.logger.info('Encrypting connection.')
    await connections[0].encrypt()

    self.logger.info('Waiting for encryption results.')
    await asyncio.gather(*encryption_results)

  # Wait for 10 seconds, or until the disconnections are received.
  async with self.assert_timeout(
      _DEFAULT_CONNECTION_TIMEOUT_SECONDS,
      msg='Keep connection for 10 seconds.',
  ):
    await disconnection.get()

Tests getting remote features.

Test steps
  1. Create a Bluetooth LE connection.
  2. Get remote features from the devices.

Parameters:

Name Type Description Default
direction Direction

The direction of the connection.

required
Source code in navi/tests/firmware/le_connection_test.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_get_remote_features(
    self, direction: constants.Direction
) -> None:
  """Tests getting remote features.

  Test steps:
    1. Create a Bluetooth LE connection.
    2. Get remote features from the devices.

  Args:
    direction: The direction of the connection.
  """
  connections = await self.test_connect(direction)

  async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
    self.logger.info('[Central] Get remote features.')
    await connections[0].get_remote_le_features()
    self.logger.info('[Peripheral] Get remote features.')
    await connections[1].get_remote_le_features()

Tests setting phy.

Test steps
  1. Create a Bluetooth LE connection.
  2. Set phy to tx: LE_2M, rx: LE_2M.
  3. Set phy to tx: LE_1M, rx: LE_1M.
  4. Set phy to tx: LE_CODED, rx: LE_CODED.
  5. Verify that the connection is not dropped.

Parameters:

Name Type Description Default
direction Direction

The direction of the connection.

required
Source code in navi/tests/firmware/le_connection_test.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
@navi_test_base.parameterized(
    constants.Direction.INCOMING, constants.Direction.OUTGOING
)
async def test_set_phy(self, direction: constants.Direction) -> None:
  """Tests setting phy.

  Test steps:
    1. Create a Bluetooth LE connection.
    2. Set phy to tx: LE_2M, rx: LE_2M.
    3. Set phy to tx: LE_1M, rx: LE_1M.
    4. Set phy to tx: LE_CODED, rx: LE_CODED.
    3. Verify that the connection is not dropped.

  Args:
    direction: The direction of the connection.
  """
  connections = await self.test_connect(direction)

  for phy in [hci.Phy.LE_2M, hci.Phy.LE_1M, hci.Phy.LE_CODED]:
    async with self.assert_not_timeout(_DEFAULT_CONNECTION_TIMEOUT_SECONDS):
      phy_results: list[asyncio.Future[core.ConnectionPHY]] = [
          asyncio.get_running_loop().create_future() for _ in range(2)
      ]
      for connection, phy_result in zip(connections, phy_results):
        connection.once(
            connection.EVENT_CONNECTION_PHY_UPDATE, phy_result.set_result
        )
        connection.once(
            connection.EVENT_CONNECTION_PHY_UPDATE_FAILURE,
            functools.partial(
                lambda result, reason: result.set_exception(
                    hci.HCI_Error(reason)
                ),
                phy_result,
            ),
        )
      self.logger.info('Setting phy to tx: %s, rx: %s', phy, phy)
      await connections[0].set_phy(tx_phys=[phy], rx_phys=[phy])

      updated_phys = await asyncio.gather(*phy_results)
      self.logger.info('Updated phys: %s', updated_phys)

      self.assertEqual(updated_phys[0].tx_phy, phy)
      self.assertEqual(updated_phys[0].rx_phy, phy)

Tests updating LE connection parameters during transmission.

Test steps
  1. Create a Bluetooth LE connection.
  2. Send l2cap data packet to the devices.
  3. Update the LE connection parameters.
  4. Verify that the connection is not dropped.
Source code in navi/tests/firmware/le_connection_test.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
async def test_update_le_connection(self) -> None:
  """Tests updating LE connection parameters during transmission.

  Test steps:
    1. Create a Bluetooth LE connection.
    2. Send l2cap data packet to the devices.
    3. Update the LE connection parameters.
    4. Verify that the connection is not dropped.
  """
  self.logger.info('Create Bluetooth LE connection.')
  connection_parameters_preferences = {
      hci.Phy.LE_1M: device_lib.ConnectionParametersPreferences(
          connection_interval_min=24 * 1.25,
          connection_interval_max=40 * 1.25,
          max_latency=0,
          supervision_timeout=500 * 10,
      )
  }
  connections = await self.create_connection(
      self.dut.device,
      self.ref.device,
      core.PhysicalTransport.LE,
      connection_parameters=connection_parameters_preferences,
  )

  disconnection = asyncio.Queue[int]()
  for connection in connections:
    connection.on(connection.EVENT_DISCONNECTION, disconnection.put_nowait)

  connections[0].send_l2cap_pdu(0, bytes(50_000))
  connections[1].send_l2cap_pdu(0, bytes(50_000))

  async with self.assert_not_timeout(
      _DEFAULT_UPDATE_CONNECTION_TIMEOUT_SECONDS
  ):
    parameter_update_results: list[asyncio.Future[None]] = [
        asyncio.get_running_loop().create_future() for _ in range(2)
    ]
    for connection, parameter_update_result in zip(
        connections, parameter_update_results
    ):
      connection.once(
          connection.EVENT_CONNECTION_PARAMETERS_UPDATE,
          functools.partial(parameter_update_result.set_result, None),
      )
      connection.once(
          connection.EVENT_CONNECTION_PARAMETERS_UPDATE_FAILURE,
          functools.partial(
              lambda result, reason: result.set_exception(
                  hci.HCI_Error(reason)
              ),
              parameter_update_result,
          ),
      )

    self.logger.info('Updating connection parameters.')
    await connections[0].update_parameters(
        connection_interval_min=8,
        connection_interval_max=16,
        max_latency=0,
        supervision_timeout=500,
    )

    self.logger.info('Waiting for parameter update results.')
    await asyncio.gather(*parameter_update_results)

  # Wait for 10 seconds, or until the disconnections are received.
  async with self.assert_timeout(
      _DEFAULT_CONNECTION_TIMEOUT_SECONDS,
      msg='Keep connection for 10 seconds.',
  ):
    await disconnection.get()

Bases: _FirmwareTestBase

Base class for dual device firmware tests.

Source code in navi/tests/firmware/test_base.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class DualDeviceTestBase(_FirmwareTestBase):
  """Base class for dual device firmware tests."""

  NUMBLE_OF_DEVICES = 2
  dut: crown.CrownDevice
  ref: crown.CrownDevice

  @override
  async def async_setup_class(self):
    await super().async_setup_class()
    self.dut, self.ref = self._devices

  @retry_lib.retry_on_exception(initial_delay_sec=1, num_retries=3)
  async def create_connection(
      self,
      central: bumble_device.Device,
      peripheral: bumble_device.Device,
      link_type: core.PhysicalTransport,
      connection_parameters: (
          Mapping[hci.Phy, bumble_device.ConnectionParametersPreferences] | None
      ) = None,
      timeout: float = _DEFAULT_STEP_TIMEOUT_SECONDS,
  ) -> tuple[bumble_device.Connection, bumble_device.Connection]:
    """Create the Bluetooth ACL link between the central and peripheral devices.

    And divide the ACL connection with BREDR and LE.

    Args:
      central: The central device to create the connection.
      peripheral: The peripheral device to accept the connection from central.
      link_type: The link type to connect. BREDR or LE.
      connection_parameters: The connection parameters to use.
      timeout: The timeout to wait for the connection to be established.

    Returns:
      A tuple of the central and peripheral connections.

    Raises:
      ValueError: If the link type is not supported.
    """
    peripheral_connections = asyncio.Queue[bumble_device.Connection]()
    peripheral.on(
        peripheral.EVENT_CONNECTION, peripheral_connections.put_nowait
    )

    async with self.assert_not_timeout(timeout, "Making connection"):
      if link_type == core.BT_BR_EDR_TRANSPORT:
        central_connection = await central.connect(
            peripheral.public_address, transport=link_type
        )
      elif link_type == core.BT_LE_TRANSPORT:
        await peripheral.start_advertising(
            own_address_type=hci.OwnAddressType.RANDOM
        )
        central_connection = await central.connect(
            peripheral.random_address,
            transport=core.BT_LE_TRANSPORT,
            connection_parameters_preferences=dict(connection_parameters)
            if connection_parameters
            else None,
        )
        await central_connection.get_remote_le_features()
      else:
        raise ValueError(f"Unsupported link type: {link_type}")
      peripheral_connection = await peripheral_connections.get()
    return central_connection, peripheral_connection

  async def encrypt_connection(
      self,
      connections: tuple[bumble_device.Connection, bumble_device.Connection],
      ltk: bytes | None = None,
      timeout: float = _DEFAULT_STEP_TIMEOUT_SECONDS,
  ) -> None:
    """Encrypt the Bluetooth ACL link.

    Args:
      connections: The connections to encrypt.
      ltk: The Long-Term Key to use.
      timeout: The timeout to wait for the encryption to complete.
    """
    # Inject pairing keys to the devices.
    pairing_keys = keys.PairingKeys()
    pairing_keys.ltk = keys.PairingKeys.Key(
        ltk or secrets.token_bytes(16), authenticated=True
    )
    for connection in connections:
      await connection.device.update_keys(
          str(connection.peer_address), pairing_keys
      )

    encryption_events = [asyncio.Event() for _ in range(2)]
    for connection, encryption_event in zip(connections, encryption_events):

      def on_encryption_change(event: asyncio.Event):
        event.set()

      connection.once(
          connection.EVENT_CONNECTION_ENCRYPTION_CHANGE,
          functools.partial(on_encryption_change, encryption_event),
      )

    async with self.assert_not_timeout(timeout):
      self.logger.info("Encrypting connection.")
      await connections[0].encrypt()
      self.logger.info("Waiting for encryption on initiator.")
      await encryption_events[0].wait()
      self.logger.info("Waiting for encryption on responder.")
      await encryption_events[1].wait()

Bases: _FirmwareTestBase

Base class for single device firmware tests.

Source code in navi/tests/firmware/test_base.py
141
142
143
144
145
146
147
148
149
150
151
152
class SingleDeviceTestBase(_FirmwareTestBase):
  """Base class for single device firmware tests."""

  NUMBLE_OF_DEVICES = 1
  dut: crown.CrownDevice
  dut_android_device: android_device.AndroidDevice

  @override
  async def async_setup_class(self):
    await super().async_setup_class()
    self.dut = self._devices[0]
    self.dut_android_device = self._android_devices[0]

Bases: BaseTestBase

Base class for firmware tests.

Source code in navi/tests/firmware/test_base.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class _FirmwareTestBase(navi_test_base.BaseTestBase):
  """Base class for firmware tests."""

  NUMBLE_OF_DEVICES: int
  _devices: list[crown.CrownDevice]
  _android_devices: list[android_device.AndroidDevice]

  @override
  async def async_setup_class(self):
    await super().async_setup_class()
    match self.user_params.get("crown_driver", _CrownDriver.ANDROID):
      case _CrownDriver.ANDROID:
        self._android_devices = self._get_android_controllers(
            self.NUMBLE_OF_DEVICES
        )
        self._devices = [
            await crown.CrownDevice.from_android_device(device)
            for device in self._android_devices
        ]
      case _CrownDriver.PASSTHROUGH:
        self._android_devices = self._get_android_controllers(1)
        crown_driver_specs = self.user_params.get("crown_driver_specs", "")
        if isinstance(crown_driver_specs, str):
          crown_driver_specs = [
              spec for spec in crown_driver_specs.split(",") if spec
          ]
        self._devices = [
            await crown.CrownDevice.from_android_device(device)
            for device in self._android_devices
        ] + [
            await crown.CrownDevice.create(crown.CrownAdapter(hci_spec))
            for hci_spec in crown_driver_specs
        ]
      case _:
        raise ValueError("Unsupported Crown driver")

  @override
  @retry_lib.retry_on_exception()
  async def async_setup_test(self):
    await super().async_setup_test()
    async with self.assert_not_timeout(_RESET_TIMEOUT_SECONDS):
      try:
        await asyncio.gather(*[device.reset() for device in self._devices])
      except ExceptionGroup as e:
        for exc in e.exceptions:
          self.logger.exception(f"Device reset failed: {exc}")
    if self.user_params.get("enable_btrt"):
      for dev in self._devices:
        await dev.device.send_command(_BTRT_ENABLE_COMMAND)

  @override
  async def async_teardown_class(self):
    await super().async_teardown_class()
    async with self.assert_not_timeout(_RESET_TIMEOUT_SECONDS):
      try:
        await asyncio.gather(*[device.close() for device in self._devices])
      except ExceptionGroup as e:
        for exc in e.exceptions:
          self.logger.exception(f"Device close failed: {exc}")

    for device in self._devices:
      device.adapter.stop()

  def _get_btsnoop(self) -> None:
    for device in self._devices:
      with open(
          pathlib.Path(
              self.current_test_info.output_path,
              f"bumble_{device.address}_btsnoop.log",
          ),
          "wb",
      ) as f:
        f.write(device.snoop_buffer.getvalue())
      if isinstance(device.adapter, crown.AndroidCrownAdapter):
        adb_snippets.download_btsnoop(
            device=device.adapter.ad,
            destination_base_path=self.current_test_info.output_path,
            filename_prefix="bumble",
        )
        adb_snippets.cleanup_btsnoop(device=device.adapter.ad)

  @override
  def on_fail(self, record: records.TestResultRecord) -> None:
    self._get_btsnoop()

  @override
  def on_pass(self, record: records.TestResultRecord) -> None:
    self._get_btsnoop()

Bases: DualDeviceTestBase

Tests throughput of different transport.

Note that the performance could be affected a lot by the HCI throughput and latency on Bumble. For example, running this test on a Cloudtop with Pontis might lead to lower bandwidth in comparison to running on a local machine.

Source code in navi/tests/firmware/throughput_test.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class ThroughputTest(test_base.DualDeviceTestBase):
  """Tests throughput of different transport.

  Note that the performance could be affected a lot by the HCI throughput and
  latency on Bumble. For example, running this test on a Cloudtop with Pontis
  might lead to lower bandwidth in comparison to running on a local machine.
  """

  @override
  async def async_setup_class(self) -> None:
    await super().async_setup_class()
    # Disable logging of bumble modules to avoid log spam.
    for module in _BUMBLE_SPAM_MODULES:
      module.logger.setLevel(logging.INFO)

  @override
  async def async_teardown_class(self) -> None:
    await super().async_teardown_class()
    # Re-enable logging of bumble modules.
    for module in _BUMBLE_SPAM_MODULES:
      module.logger.setLevel(logging.DEBUG)

  @override
  async def async_setup_test(self) -> None:
    await super().async_setup_test()

    # Using highest authentication level to allow secure sockets.
    self.ref.device.pairing_config_factory = lambda _: pairing.PairingConfig(
        delegate=_PairingDelegate(
            io_capability=(
                _PairingDelegate.IoCapability.DISPLAY_OUTPUT_AND_YES_NO_INPUT
            )
        )
    )

  @navi_test_base.retry(2)
  async def test_rfcomm(self) -> None:
    """Tests RFCOMM throughput."""

    connection = await self.create_connection(
        self.dut.device,
        self.ref.device,
        core.BT_BR_EDR_TRANSPORT,
    )

    ref_accept_future: asyncio.Future[rfcomm.DLC] = (
        asyncio.get_running_loop().create_future()
    )
    channel = rfcomm.Server(self.ref.device).listen(
        acceptor=ref_accept_future.set_result
    )
    self.logger.info("[REF] Listen RFCOMM on channel %d.", channel)

    self.logger.info("[DUT] Connect RFCOMM channel to REF.")
    rfcomm_multiplexer = await rfcomm.Client(connection[0]).start()
    async with self.assert_not_timeout(_DEFAULT_STEP_TIMEOUT_SECONDS):
      ref_dut_dlc, dut_ref_dlc = await asyncio.gather(
          ref_accept_future,
          rfcomm_multiplexer.open_dlc(channel)
      )

    # Store received SDUs in queue.
    ref_sdu_rx_queue = asyncio.Queue[bytes]()
    ref_dut_dlc.sink = ref_sdu_rx_queue.put_nowait
    # Set the threshold to 6 to avoid running out of buffer.
    ref_dut_dlc.rx_credits_threshold = _RX_THRESHOLD
    total_bytes = 4 * 1024 * 1024  # 4 MB

    async def ref_rx_task():
      bytes_received = 0
      while bytes_received < total_bytes:
        bytes_received += len(await ref_sdu_rx_queue.get())

    self.logger.info("Start sending data from DUT to REF")
    with performance_tool.Stopwatch() as tx_stopwatch:
      async with self.assert_not_timeout(_TRANSMISSION_TIMEOUT_SECONDS):
        dut_ref_dlc.write(bytes(total_bytes))
        await ref_rx_task()

    dut_sdu_rx_queue = asyncio.Queue[bytes]()
    dut_ref_dlc.sink = dut_sdu_rx_queue.put_nowait
    # Set the threshold to 6 to avoid running out of buffer.
    dut_ref_dlc.rx_credits_threshold = _RX_THRESHOLD

    async def dut_rx_task():
      bytes_received = 0
      while bytes_received < total_bytes:
        bytes_received += len(await dut_sdu_rx_queue.get())

    self.logger.info("Start sending data from REF to DUT")
    with performance_tool.Stopwatch() as rx_stopwatch:
      async with self.assert_not_timeout(_TRANSMISSION_TIMEOUT_SECONDS):
        ref_dut_dlc.write(bytes(total_bytes))
        await dut_rx_task()

    tx_throughput = total_bytes / (tx_stopwatch.elapsed_time).total_seconds()
    rx_throughput = total_bytes / (rx_stopwatch.elapsed_time).total_seconds()
    self.logger.info("Tx Throughput: %.2f KB/s", tx_throughput / 1024)
    self.logger.info("Rx Throughput: %.2f KB/s", rx_throughput / 1024)
    self.record_data(
        navi_test_base.RecordData(
            test_name=self.current_test_info.name,
            properties={
                "tx_throughput_bytes_per_second": tx_throughput,
                "rx_throughput_bytes_per_second": rx_throughput,
            },
        )
    )

Tests RFCOMM throughput.

Source code in navi/tests/firmware/throughput_test.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@navi_test_base.retry(2)
async def test_rfcomm(self) -> None:
  """Tests RFCOMM throughput."""

  connection = await self.create_connection(
      self.dut.device,
      self.ref.device,
      core.BT_BR_EDR_TRANSPORT,
  )

  ref_accept_future: asyncio.Future[rfcomm.DLC] = (
      asyncio.get_running_loop().create_future()
  )
  channel = rfcomm.Server(self.ref.device).listen(
      acceptor=ref_accept_future.set_result
  )
  self.logger.info("[REF] Listen RFCOMM on channel %d.", channel)

  self.logger.info("[DUT] Connect RFCOMM channel to REF.")
  rfcomm_multiplexer = await rfcomm.Client(connection[0]).start()
  async with self.assert_not_timeout(_DEFAULT_STEP_TIMEOUT_SECONDS):
    ref_dut_dlc, dut_ref_dlc = await asyncio.gather(
        ref_accept_future,
        rfcomm_multiplexer.open_dlc(channel)
    )

  # Store received SDUs in queue.
  ref_sdu_rx_queue = asyncio.Queue[bytes]()
  ref_dut_dlc.sink = ref_sdu_rx_queue.put_nowait
  # Set the threshold to 6 to avoid running out of buffer.
  ref_dut_dlc.rx_credits_threshold = _RX_THRESHOLD
  total_bytes = 4 * 1024 * 1024  # 4 MB

  async def ref_rx_task():
    bytes_received = 0
    while bytes_received < total_bytes:
      bytes_received += len(await ref_sdu_rx_queue.get())

  self.logger.info("Start sending data from DUT to REF")
  with performance_tool.Stopwatch() as tx_stopwatch:
    async with self.assert_not_timeout(_TRANSMISSION_TIMEOUT_SECONDS):
      dut_ref_dlc.write(bytes(total_bytes))
      await ref_rx_task()

  dut_sdu_rx_queue = asyncio.Queue[bytes]()
  dut_ref_dlc.sink = dut_sdu_rx_queue.put_nowait
  # Set the threshold to 6 to avoid running out of buffer.
  dut_ref_dlc.rx_credits_threshold = _RX_THRESHOLD

  async def dut_rx_task():
    bytes_received = 0
    while bytes_received < total_bytes:
      bytes_received += len(await dut_sdu_rx_queue.get())

  self.logger.info("Start sending data from REF to DUT")
  with performance_tool.Stopwatch() as rx_stopwatch:
    async with self.assert_not_timeout(_TRANSMISSION_TIMEOUT_SECONDS):
      ref_dut_dlc.write(bytes(total_bytes))
      await dut_rx_task()

  tx_throughput = total_bytes / (tx_stopwatch.elapsed_time).total_seconds()
  rx_throughput = total_bytes / (rx_stopwatch.elapsed_time).total_seconds()
  self.logger.info("Tx Throughput: %.2f KB/s", tx_throughput / 1024)
  self.logger.info("Rx Throughput: %.2f KB/s", rx_throughput / 1024)
  self.record_data(
      navi_test_base.RecordData(
          test_name=self.current_test_info.name,
          properties={
              "tx_throughput_bytes_per_second": tx_throughput,
              "rx_throughput_bytes_per_second": rx_throughput,
          },
      )
  )