bt_broadcast_assistant/assistant/
peer.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use bt_gatt::pii::GetPeerAddr;
6use futures::stream::FusedStream;
7use futures::Stream;
8use std::sync::Arc;
9use thiserror::Error;
10
11use bt_bap::types::BroadcastId;
12use bt_bass::client::error::Error as BassClientError;
13use bt_bass::client::event::Event as BassEvent;
14use bt_bass::client::BroadcastAudioScanServiceClient;
15#[cfg(any(test, feature = "debug"))]
16use bt_bass::types::BroadcastReceiveState;
17use bt_bass::types::{BisSync, PaSync};
18use bt_common::core::PaInterval;
19use bt_common::packet_encoding::Error as PacketError;
20use bt_common::PeerId;
21#[cfg(any(test, feature = "debug"))]
22use bt_gatt::types::Handle;
23use std::collections::HashMap;
24
25use crate::assistant::DiscoveredBroadcastSources;
26
27#[derive(Debug, Error)]
28pub enum Error {
29    #[error("Failed to take event stream at Broadcast Audio Scan Service client")]
30    UnavailableBassEventStream,
31
32    #[error("Broadcast Audio Scan Service client error: {0:?}")]
33    BassClient(#[from] BassClientError),
34
35    #[error("Incomplete information for broadcast source with peer id ({0})")]
36    NotEnoughInfo(PeerId),
37
38    #[error("Broadcast source with peer id ({0}) does not exist")]
39    DoesNotExist(PeerId),
40
41    #[error("Failed to lookup address for peer id ({0}): {1:?}")]
42    AddressLookupError(PeerId, bt_gatt::types::Error),
43
44    #[error("Packet error: {0}")]
45    PacketError(#[from] PacketError),
46}
47
48/// Connected scan delegator peer. Clients can use this
49/// object to perform Broadcast Audio Scan Service operations on the
50/// scan delegator peer.
51/// Not thread-safe and only one operation must be done at a time.
52pub struct Peer<T: bt_gatt::GattTypes> {
53    peer_id: PeerId,
54    // Keep for peer connection.
55    _client: T::Client,
56    bass: BroadcastAudioScanServiceClient<T>,
57    // TODO(b/309015071): add a field for pacs.
58    broadcast_sources: Arc<DiscoveredBroadcastSources>,
59}
60
61impl<T: bt_gatt::GattTypes> Peer<T> {
62    pub(crate) fn new(
63        peer_id: PeerId,
64        client: T::Client,
65        bass: BroadcastAudioScanServiceClient<T>,
66        broadcast_sources: Arc<DiscoveredBroadcastSources>,
67    ) -> Self {
68        Peer { peer_id, _client: client, bass, broadcast_sources }
69    }
70
71    pub fn peer_id(&self) -> PeerId {
72        self.peer_id
73    }
74
75    /// Takes event stream for BASS events from this scan delegator peer.
76    /// Clients can call this method to start subscribing to BASS events.
77    pub fn take_event_stream(
78        &mut self,
79    ) -> Result<impl Stream<Item = Result<BassEvent, BassClientError>> + FusedStream, Error> {
80        self.bass.take_event_stream().ok_or(Error::UnavailableBassEventStream)
81    }
82
83    /// Send broadcast code for a particular broadcast.
84    pub async fn send_broadcast_code(
85        &self,
86        broadcast_id: BroadcastId,
87        broadcast_code: [u8; 16],
88    ) -> Result<(), Error> {
89        self.bass.set_broadcast_code(broadcast_id, broadcast_code).await.map_err(Into::into)
90    }
91
92    /// Sends a command to add a particular broadcast source.
93    ///
94    /// # Arguments
95    ///
96    /// * `broadcast_source_pid` - peer id of the braodcast source that's to be
97    ///   added to this scan delegator peer
98    /// * `address_lookup` - An implementation of [`GetPeerAddr`] that will be
99    ///   used to look up the peer's address.
100    /// * `pa_sync` - pa sync mode the peer should attempt to be in
101    /// * `bis_sync` - desired BIG to BIS synchronization information. If the
102    ///   set is empty, no preference value is used for all the BIGs
103    pub async fn add_broadcast_source(
104        &self,
105        source_peer_id: PeerId,
106        address_lookup: &impl GetPeerAddr,
107        pa_sync: PaSync,
108        bis_sync: HashMap<u8, BisSync>,
109    ) -> Result<(), Error> {
110        let mut broadcast_source = self
111            .broadcast_sources
112            .get_by_peer_id(&source_peer_id)
113            .ok_or(Error::DoesNotExist(source_peer_id))?;
114
115        let (broadcast_addr, broadcast_addr_type) = address_lookup
116            .get_peer_address(source_peer_id)
117            .await
118            .map_err(|err| Error::AddressLookupError(source_peer_id, err))?;
119        broadcast_source.with_address(broadcast_addr).with_address_type(broadcast_addr_type);
120
121        if !broadcast_source.into_add_source() {
122            return Err(Error::NotEnoughInfo(source_peer_id));
123        }
124
125        self.bass
126            .add_broadcast_source(
127                broadcast_source.broadcast_id.unwrap(),
128                broadcast_source.address_type.unwrap(),
129                broadcast_source.address.unwrap(),
130                broadcast_source.advertising_sid.unwrap(),
131                pa_sync,
132                broadcast_source.pa_interval.unwrap_or(PaInterval::unknown()),
133                broadcast_source.endpoint_to_big_subgroups(bis_sync).map_err(Error::PacketError)?,
134            )
135            .await
136            .map_err(Into::into)
137    }
138
139    /// Sends a command to to update a particular broadcast source's PA sync.
140    ///
141    /// # Arguments
142    ///
143    /// * `broadcast_id` - broadcast id of the broadcast source that's to be
144    ///   updated
145    /// * `pa_sync` - pa sync mode the scan delegator peer should attempt to be
146    ///   in.
147    /// * `bis_sync` - desired BIG to BIS synchronization information
148    pub async fn update_broadcast_source_sync(
149        &self,
150        broadcast_id: BroadcastId,
151        pa_sync: PaSync,
152        bis_sync: HashMap<u8, BisSync>,
153    ) -> Result<(), Error> {
154        let pa_interval = self
155            .broadcast_sources
156            .get_by_broadcast_id(&broadcast_id)
157            .map(|bs| bs.pa_interval)
158            .unwrap_or(None);
159
160        self.bass
161            .modify_broadcast_source(broadcast_id, pa_sync, pa_interval, Some(bis_sync), None)
162            .await
163            .map_err(Into::into)
164    }
165
166    /// Sends a command to remove a particular broadcast source.
167    ///
168    /// # Arguments
169    ///
170    /// * `broadcast_id` - broadcast id of the braodcast source that's to be
171    ///   removed from the scan delegator
172    pub async fn remove_broadcast_source(&self, broadcast_id: BroadcastId) -> Result<(), Error> {
173        self.bass.remove_broadcast_source(broadcast_id).await.map_err(Into::into)
174    }
175
176    /// Sends a command to inform the scan delegator peer that we have
177    /// started scanning for broadcast sources on behalf of it.
178    pub async fn inform_remote_scan_started(&self) -> Result<(), Error> {
179        self.bass.remote_scan_started().await.map_err(Into::into)
180    }
181
182    /// Sends a command to inform the scan delegator peer that we have
183    /// stopped scanning for broadcast sources on behalf of it.
184    pub async fn inform_remote_scan_stopped(&self) -> Result<(), Error> {
185        self.bass.remote_scan_stopped().await.map_err(Into::into)
186    }
187
188    /// Returns a list of BRS characteristics' latest values the scan delegator
189    /// has received.
190    #[cfg(any(test, feature = "debug"))]
191    pub fn get_broadcast_receive_states(&self) -> Vec<(Handle, BroadcastReceiveState)> {
192        self.bass.known_broadcast_sources()
193    }
194}
195
196#[cfg(test)]
197pub(crate) mod tests {
198    use super::*;
199
200    use assert_matches::assert_matches;
201    use bt_gatt::pii::StaticPeerAddr;
202    use futures::{pin_mut, FutureExt};
203    use std::collections::HashMap;
204    use std::task::Poll;
205
206    use bt_common::core::{AddressType, AdvertisingSetId};
207    use bt_gatt::test_utils::{FakeClient, FakeGetPeerAddr, FakePeerService, FakeTypes};
208    use bt_gatt::types::{
209        AttributePermissions, CharacteristicProperties, CharacteristicProperty, Handle,
210    };
211
212    use bt_gatt::Characteristic;
213
214    use crate::types::BroadcastSource;
215
216    const RECEIVE_STATE_HANDLE: Handle = Handle(0x11);
217    const AUDIO_SCAN_CONTROL_POINT_HANDLE: Handle = Handle(0x12);
218
219    pub(crate) fn fake_bass_service() -> FakePeerService {
220        let mut peer_service = FakePeerService::new();
221        // One broadcast receive state and one broadcast audio scan control
222        // point characteristic handles.
223        peer_service.add_characteristic(
224            Characteristic {
225                handle: RECEIVE_STATE_HANDLE,
226                uuid: bt_bass::types::BROADCAST_RECEIVE_STATE_UUID,
227                properties: CharacteristicProperties(vec![
228                    CharacteristicProperty::Broadcast,
229                    CharacteristicProperty::Notify,
230                ]),
231                permissions: AttributePermissions::default(),
232                descriptors: vec![],
233            },
234            vec![],
235        );
236        peer_service.add_characteristic(
237            Characteristic {
238                handle: AUDIO_SCAN_CONTROL_POINT_HANDLE,
239                uuid: bt_bass::types::BROADCAST_AUDIO_SCAN_CONTROL_POINT_UUID,
240                properties: CharacteristicProperties(vec![CharacteristicProperty::Broadcast]),
241                permissions: AttributePermissions::default(),
242                descriptors: vec![],
243            },
244            vec![],
245        );
246        peer_service
247    }
248
249    fn setup() -> (Peer<FakeTypes>, FakePeerService, Arc<DiscoveredBroadcastSources>) {
250        let peer_service = fake_bass_service();
251
252        let broadcast_sources = DiscoveredBroadcastSources::new();
253        (
254            Peer {
255                peer_id: PeerId(0x1),
256                _client: FakeClient::new(),
257                bass: BroadcastAudioScanServiceClient::<FakeTypes>::create_for_test(
258                    peer_service.clone(),
259                    Handle(0x1),
260                ),
261                broadcast_sources: broadcast_sources.clone(),
262            },
263            peer_service,
264            broadcast_sources,
265        )
266    }
267
268    #[test]
269    fn take_event_stream() {
270        let (mut peer, _peer_service, _broadcast_source) = setup();
271        let _event_stream = peer.take_event_stream().expect("should succeed");
272
273        // If we try to take the event stream the second time, it should fail.
274        assert!(peer.take_event_stream().is_err());
275    }
276
277    #[test]
278    fn add_broadcast_source_fail() {
279        let (peer, _peer_service, broadcast_source) = setup();
280
281        let mut noop_cx = futures::task::Context::from_waker(futures::task::noop_waker_ref());
282
283        // Should fail because broadcast source doesn't exist.
284        {
285            let fut = peer.add_broadcast_source(
286                PeerId(1001),
287                &FakeGetPeerAddr,
288                PaSync::SyncPastUnavailable,
289                HashMap::new(),
290            );
291            pin_mut!(fut);
292            let polled = fut.poll_unpin(&mut noop_cx);
293            assert_matches!(polled, Poll::Ready(Err(Error::DoesNotExist(_))));
294        }
295
296        let _ = broadcast_source.merge_broadcast_source_data(
297            &PeerId(1001),
298            &BroadcastSource::default()
299                .with_advertising_sid(AdvertisingSetId(1))
300                .with_broadcast_id(BroadcastId::try_from(1001).unwrap()),
301        );
302
303        // Should fail because peer address couldn't be looked up.
304        {
305            let address_lookup =
306                StaticPeerAddr::new_for_peer(PeerId(1002), [1, 2, 3, 4, 5, 6], AddressType::Public);
307            let fut = peer.add_broadcast_source(
308                PeerId(1001),
309                &address_lookup,
310                PaSync::SyncPastUnavailable,
311                HashMap::new(),
312            );
313            pin_mut!(fut);
314            let polled = fut.poll_unpin(&mut noop_cx);
315            assert_matches!(polled, Poll::Ready(Err(Error::AddressLookupError(_, _))));
316        }
317
318        // Should fail because not enough information.
319        {
320            let address_lookup =
321                StaticPeerAddr::new_for_peer(PeerId(1001), [1, 2, 3, 4, 5, 6], AddressType::Public);
322            let fut = peer.add_broadcast_source(
323                PeerId(1001),
324                &address_lookup,
325                PaSync::SyncPastUnavailable,
326                HashMap::new(),
327            );
328            pin_mut!(fut);
329            let polled = fut.poll_unpin(&mut noop_cx);
330            assert_matches!(polled, Poll::Ready(Err(Error::NotEnoughInfo(_))));
331        }
332    }
333}