1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// This module defines common primitives for building and working with Harness types that rely on
/// interacting with bt-hci-emulator state.
///
/// There is no single 'EmulatorHarness' type; instead many different harness types can be built
/// that provide access to emulator behavior. To provide such harness functionality usually requires
/// two things:
///
///    - Providing access to a value of type `EmulatorState` within the Harness's State type, by
///      implementing `AsMut<EmulatorState>` on the state type
///    - Providing access to a fidl proxy of type `HciEmulatorProxy`, by implementing
///      `AsRef<HciEmulatorProxy>` on the auxilliary (Aux) type
///
/// This module defines the `EmulatorState` type, which represents the state common to the hci
/// emulator. It also provides common functionality for working with emulator behavior via this
/// state and via the HciEmulatorProxy.
///
/// The `expectation` submodule provides useful expectations (see `fuchsia_bluetooth::expectation`)
/// that can be used to write idiomatic testcases using these harnesses.
///
/// An example implementation of an Emulator harness may look like the following:
///
/// First, define our state type, nesting the `EmulatorState` within:
///
///     ```
///     #[derive(Clone, Debug, Default)]
///     pub struct PeripheralState {
///         emulator_state: EmulatorState,
///         connections: Vec<(Peer, ConnectionProxy)>,
///     }
///     ```
///
/// Then, define `AsMut` and `AsRef` implementations to provide access to the inner EmulatorState
///
///     ```
///     impl AsMut<EmulatorState> for PeripheralState {
///         fn as_mut(&mut self) -> &mut EmulatorState {
///             &mut self.emulator_state
///         }
///     }
///     impl AsRef<EmulatorState> for PeripheralState {
///         fn as_ref(&self) -> &EmulatorState {
///             &self.emulator_state
///         }
///     }
///     ```
///
/// Then, define an auxilliary type including the `HciEmulatorProxy`, and also implement `AsRef`:
///
///     ```
///     pub struct Aux {
///         peripheral: PeripheralProxy,
///         emulator: HciEmulatorProxy,
///     }
///     impl AsRef<HciEmulatorProxy> for Aux {
///         fn as_ref(&self) -> &HciEmulatorProxy {
///             &self.emulator
///         }
///     }
///     ```
///
/// Then we can build our harness by combining these two types:
///
///     ```
///     #[derive(Clone)]
///     pub struct PeripheralHarness(Expectable<PeripheralState, Aux>);
///     ```
///
/// Then we can use this harness to track emulator state and trigger expectations:
///
///     ```
///     // Start watching advertising events
///     let harness = PeripheralHarness::new(...);
///     fasync::Task::spawn(
///         watch_advertising_states(harness.deref().clone()).unwrap_or_else(|_| ())).detach();
///     let _ = harness.when_satisfied(emulator::expectation::advertising_is_enabled(true)).await?;
///     ```
use {
    anyhow::{format_err, Error},
    fidl_fuchsia_bluetooth::{DeviceClass, MAJOR_DEVICE_CLASS_TOY},
    fidl_fuchsia_bluetooth_test::{
        AdvertisingData, BredrPeerParameters, ConnectionState, HciEmulatorProxy,
        LowEnergyPeerParameters, PeerProxy,
    },
    fuchsia_bluetooth::{
        expectation::asynchronous::{ExpectableExt, ExpectableState},
        types::Address,
    },
    futures::{
        future::{err, Either},
        Future,
    },
    hci_emulator_client::types::{ControllerParameters, LegacyAdvertisingState},
    std::{collections::HashMap, convert::AsRef},
};

/// The URL of the platform bus driver. The bt-hci-emulator driver is a legacy driver, which binds
/// under the platform-bus instead of the test-root driver. Because this is non-standard behavior,
/// we have to provide this URL to the Driver Test Realm.
pub(crate) const EMULATOR_ROOT_DRIVER_URL: &str =
    "fuchsia-boot:///platform-bus#meta/platform-bus.cm";

/// Used to maintain the state transitions that are observed from the emulator. This type can be
/// used in test harness auxiliary types.
#[derive(Clone, Debug)]
pub struct EmulatorState {
    /// Most recently observed controller parameters.
    pub controller_parameters: Option<ControllerParameters>,

    /// Observed changes to the controller's advertising state and parameters.
    pub advertising_state_changes: Vec<LegacyAdvertisingState>,

    /// List of observed peer connection states.
    pub connection_states: HashMap<Address, Vec<ConnectionState>>,
}

impl Default for EmulatorState {
    fn default() -> EmulatorState {
        EmulatorState {
            controller_parameters: None,
            advertising_state_changes: vec![],
            connection_states: HashMap::new(),
        }
    }
}

pub fn default_le_peer(addr: &Address) -> LowEnergyPeerParameters {
    LowEnergyPeerParameters {
        address: Some(addr.into()),
        connectable: Some(true),
        advertisement: Some(AdvertisingData {
            data: vec![
                // Flags field set to "general discoverable"
                0x02, 0x01, 0x02, // Complete local name set to "Fake"
                0x05, 0x09, 'F' as u8, 'a' as u8, 'k' as u8, 'e' as u8,
            ],
        }),
        scan_response: None,
        ..Default::default()
    }
}

/// An emulated BR/EDR peer using default parameters commonly used in tests. The peer is set up to
/// be connectable and has the "toy" device class.
pub fn default_bredr_peer(addr: &Address) -> BredrPeerParameters {
    BredrPeerParameters {
        address: Some(addr.into()),
        connectable: Some(true),
        device_class: Some(DeviceClass { value: MAJOR_DEVICE_CLASS_TOY }),
        service_definition: None,
        ..Default::default()
    }
}

pub fn add_le_peer(
    proxy: &HciEmulatorProxy,
    parameters: LowEnergyPeerParameters,
) -> impl Future<Output = Result<PeerProxy, Error>> {
    match fidl::endpoints::create_proxy() {
        Ok((local, remote)) => {
            let fut = proxy.add_low_energy_peer(&parameters, remote);
            Either::Right(async {
                let _ = fut
                    .await?
                    .map_err(|e| format_err!("Failed to add emulated LE peer: {:?}", e))?;
                Ok(local)
            })
        }
        Err(e) => Either::Left(err(e.into())),
    }
}

pub fn add_bredr_peer(
    proxy: &HciEmulatorProxy,
    parameters: BredrPeerParameters,
) -> impl Future<Output = Result<PeerProxy, Error>> {
    match fidl::endpoints::create_proxy() {
        Ok((local, remote)) => {
            let fut = proxy.add_bredr_peer(&parameters, remote);
            Either::Right(async {
                let _ = fut
                    .await?
                    .map_err(|e| format_err!("Failed to add emulated BR/EDR peer: {:?}", e))?;
                Ok(local)
            })
        }
        Err(e) => Either::Left(err(e.into())),
    }
}

pub async fn watch_controller_parameters<H, S, A>(harness: H) -> Result<(), Error>
where
    H: ExpectableState<State = S> + ExpectableExt<S, A>,
    S: AsMut<EmulatorState> + 'static,
    A: AsRef<HciEmulatorProxy>,
{
    let proxy = HciEmulatorProxy::clone(harness.aux().as_ref());
    loop {
        let cp = proxy.watch_controller_parameters().await?;
        harness.write_state().as_mut().controller_parameters = Some(cp.into());
        harness.notify_state_changed();
    }
}

/// Record advertising state changes. The asynchronous execution doesn't complete until the
/// emulator channel gets closed or a FIDL error occurs.
pub async fn watch_advertising_states<H, S, A>(harness: H) -> Result<(), Error>
where
    H: ExpectableState<State = S> + ExpectableExt<S, A>,
    S: AsMut<EmulatorState> + 'static,
    A: AsRef<HciEmulatorProxy>,
{
    let proxy = HciEmulatorProxy::clone(harness.aux().as_ref());
    loop {
        let states = proxy.watch_legacy_advertising_states().await?;
        harness
            .write_state()
            .as_mut()
            .advertising_state_changes
            .append(&mut states.into_iter().map(|s| s.into()).collect());
        harness.notify_state_changed();
    }
}

/// Record connection state changes from the given emulated Peer. The returned Future doesn't
/// run until the `proxy` channel gets closed or a FIDL error occurs.
pub async fn watch_peer_connection_states<H, S, A>(
    harness: H,
    address: Address,
    proxy: PeerProxy,
) -> Result<(), Error>
where
    H: ExpectableState<State = S> + ExpectableExt<S, A>,
    S: AsMut<EmulatorState> + 'static,
    A: AsRef<HciEmulatorProxy>,
{
    loop {
        let mut result = proxy.watch_connection_states().await?;
        // Introduce a scope as it is important not to hold a mutable lock to the harness state when
        // we call `harness.notify_state_changed()` below.
        {
            let mut s = harness.write_state();
            let state_map = &mut s.as_mut().connection_states;
            let states = state_map.entry(address).or_insert(vec![]);
            states.append(&mut result);
        }
        harness.notify_state_changed();
    }
}

/// Utilities used for setting up expectation predicates on the HCI emulator state transitions.
pub mod expectation {
    use {
        super::*, fidl_fuchsia_bluetooth_test::LegacyAdvertisingType,
        fuchsia_bluetooth::expectation::Predicate,
    };

    pub fn local_name_is<S>(name: &'static str) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        Predicate::equal(Some(name.to_string())).over_value(
            |state: &S| {
                state
                    .as_ref()
                    .controller_parameters
                    .as_ref()
                    .and_then(|p| p.local_name.as_ref().map(|o| o.to_string()))
            },
            "controller_parameters.local_name",
        )
    }

    pub fn device_class_is<S>(device_class: DeviceClass) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        Predicate::equal(Some(device_class)).over_value(
            |state: &S| state.as_ref().controller_parameters.as_ref().and_then(|p| p.device_class),
            "controller_parameters.device_class",
        )
    }

    pub fn advertising_is_enabled<S>(enabled: bool) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        Predicate::equal(Some(enabled)).over_value(
            |state: &S| state.as_ref().advertising_state_changes.last().map(|s| s.enabled),
            "controller_parameters.device_class",
        )
    }

    pub fn advertising_was_enabled<S>(enabled: bool) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("advertising was (enabled: {})", enabled);
        Predicate::predicate(
            move |state: &S| -> bool {
                state.as_ref().advertising_state_changes.iter().any(|s| s.enabled == enabled)
            },
            &descr,
        )
    }

    pub fn advertising_type_is<S>(type_: LegacyAdvertisingType) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("advertising type is: {:#?}", type_);
        Predicate::predicate(
            move |state: &S| -> bool {
                state
                    .as_ref()
                    .advertising_state_changes
                    .last()
                    .and_then(|s| s.type_)
                    .is_some_and(|t| t == type_)
            },
            &descr,
        )
    }

    pub fn advertising_data_is<S>(data: Vec<u8>) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("advertising data is: {:#?}", data);
        Predicate::predicate(
            move |state: &S| -> bool {
                state
                    .as_ref()
                    .advertising_state_changes
                    .last()
                    .and_then(|s| s.advertising_data.as_ref())
                    .is_some_and(|a| *a == data)
            },
            &descr,
        )
    }

    pub fn scan_response_is<S>(data: Vec<u8>) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("scan response data is: {:#?}", data);
        Predicate::predicate(
            move |state: &S| -> bool {
                state
                    .as_ref()
                    .advertising_state_changes
                    .last()
                    .and_then(|s| s.scan_response.as_ref())
                    .is_some_and(|s| *s == data)
            },
            &descr,
        )
    }

    fn to_slices(ms: u16) -> u16 {
        let slices = (ms as u32) * 1000 / 625;
        slices as u16
    }

    pub fn advertising_max_interval_is<S>(interval_ms: u16) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("advertising max interval is: {:#?} ms", interval_ms);
        Predicate::predicate(
            move |state: &S| -> bool {
                state
                    .as_ref()
                    .advertising_state_changes
                    .last()
                    .and_then(|s| s.interval_max)
                    .is_some_and(|i| i == to_slices(interval_ms))
            },
            &descr,
        )
    }

    pub fn peer_connection_state_was<S>(address: Address, state: ConnectionState) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("emulated peer connection state was: {:?}", state);
        Predicate::predicate(
            move |s: &S| -> bool {
                s.as_ref().connection_states.get(&address).is_some_and(|s| s.contains(&state))
            },
            &descr,
        )
    }

    pub fn peer_connection_state_is<S>(address: Address, state: ConnectionState) -> Predicate<S>
    where
        S: 'static + AsRef<EmulatorState>,
    {
        let descr = format!("emulated peer connection state is: {:?}", state);
        Predicate::predicate(
            move |s: &S| -> bool {
                s.as_ref().connection_states.get(&address).is_some_and(|s| s.last() == Some(&state))
            },
            &descr,
        )
    }
}