bt_gatt/
pii.rs

1// Copyright 2025 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 std::future::Future;
6
7use bt_common::{
8    core::{Address, AddressType},
9    PeerId,
10};
11
12use crate::types::*;
13
14/// Takes a peer address and queries an underlying service for its actual
15/// bluetooth address and address type. Used for adding broadcast sources.
16pub trait GetPeerAddr {
17    /// Resolve peer ID to peer address and address type.
18    fn get_peer_address(
19        &self,
20        peer_id: PeerId,
21    ) -> impl Future<Output = Result<(Address, AddressType)>>;
22}
23
24/// Helper for when the peer's address is known. Always returns the given
25/// address, if any.
26pub struct StaticPeerAddr {
27    peer_id: Option<PeerId>,
28    address: Address,
29    address_type: AddressType,
30}
31
32impl StaticPeerAddr {
33    /// Returns a [`StaticPeerAddr`] that always returns the given address,
34    /// regardless of the `peer_id` being looked up.
35    pub fn new(address: Address, address_type: AddressType) -> Self {
36        Self { peer_id: None, address, address_type }
37    }
38
39    /// Returns a [`StaticPeerAddr`] that will only return successfully if the
40    /// `peer_id` matches.
41    pub fn new_for_peer(peer_id: PeerId, address: Address, address_type: AddressType) -> Self {
42        Self { peer_id: Some(peer_id), address, address_type }
43    }
44}
45
46impl GetPeerAddr for StaticPeerAddr {
47    async fn get_peer_address(&self, peer_id: PeerId) -> Result<(Address, AddressType)> {
48        if let Some(validated_peer_id) = self.peer_id {
49            if peer_id != validated_peer_id {
50                return Err(Error::PeerNotRecognized(peer_id));
51            }
52        }
53        return Ok((self.address, self.address_type));
54    }
55}