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
// Copyright 2019 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.

use fidl_fuchsia_bluetooth_sys as fsys;
use fuchsia_inspect::{self as inspect, Property};
use std::fmt;

use crate::error::Error;
use crate::inspect::{DebugExt, InspectData, Inspectable, IsInspectable, ToProperty};
use crate::types::{addresses_to_custom_string, Address, HostId};

/// `HostInfo` contains informational parameters and state for a bt-host device.
#[derive(Clone, Debug, PartialEq)]
pub struct HostInfo {
    /// Uniquely identifies a host on the current system.
    pub id: HostId,

    /// The Bluetooth technologies that are supported by this adapter.
    pub technology: fsys::TechnologyType,

    /// The known Classic and LE addresses associated with this Host.
    /// This is guaranteed to be nonempty. The Public Address is always first.
    pub addresses: Vec<Address>,

    /// Indicates whether or not this is the active host. The system has one active host which
    /// handles all Bluetooth procedures.
    pub active: bool,

    /// The local name of this host. This is the name that is visible to other devices when this
    /// host is in the discoverable mode. Not present if the local device name is unknown.
    pub local_name: Option<String>,

    /// Whether or not the local adapter is currently discoverable over BR/EDR and
    /// LE physical channels.
    pub discoverable: bool,

    /// Whether or not device discovery is currently being performed.
    pub discovering: bool,
}

impl TryFrom<&fsys::HostInfo> for HostInfo {
    type Error = Error;
    fn try_from(src: &fsys::HostInfo) -> Result<HostInfo, Self::Error> {
        let addresses = src.addresses.as_ref().ok_or(Error::missing("HostInfo.addresses"))?;
        if addresses.is_empty() {
            return Err(Error::conversion("HostInfo.addresses must be nonempty"));
        }
        let addresses = addresses.iter().map(Into::into).collect();
        Ok(HostInfo {
            id: HostId::from(src.id.ok_or(Error::missing("HostInfo.id"))?),
            technology: src.technology.ok_or(Error::missing("HostInfo.technology"))?,
            addresses,
            active: src.active.unwrap_or(false),
            local_name: src.local_name.clone(),
            discoverable: src.discoverable.unwrap_or(false),
            discovering: src.discovering.unwrap_or(false),
        })
    }
}

impl TryFrom<fsys::HostInfo> for HostInfo {
    type Error = Error;
    fn try_from(src: fsys::HostInfo) -> Result<HostInfo, Self::Error> {
        HostInfo::try_from(&src)
    }
}

impl From<&HostInfo> for fsys::HostInfo {
    fn from(src: &HostInfo) -> fsys::HostInfo {
        fsys::HostInfo {
            id: Some(src.id.into()),
            technology: Some(src.technology),
            active: Some(src.active),
            local_name: src.local_name.clone(),
            discoverable: Some(src.discoverable),
            discovering: Some(src.discovering),
            addresses: Some(src.addresses.iter().map(Into::into).collect()),
            ..Default::default()
        }
    }
}

impl From<HostInfo> for fsys::HostInfo {
    fn from(src: HostInfo) -> fsys::HostInfo {
        fsys::HostInfo::from(&src)
    }
}

impl fmt::Display for HostInfo {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(fmt, "HostInfo:")?;
        writeln!(fmt, "\tidentifier:\t{}", self.id.to_string())?;
        writeln!(fmt, "\taddresses:\t{}", addresses_to_custom_string(&self.addresses, "\n\t\t\t"))?;
        writeln!(fmt, "\tactive:\t{}", self.active)?;
        writeln!(fmt, "\ttechnology:\t{:?}", self.technology)?;
        writeln!(
            fmt,
            "\tlocal name:\t{}",
            self.local_name.as_ref().unwrap_or(&"(unknown)".to_string())
        )?;
        writeln!(fmt, "\tdiscoverable:\t{}", self.discoverable)?;
        writeln!(fmt, "\tdiscovering:\t{}", self.discovering)
    }
}

impl Inspectable<HostInfo> {
    pub fn update(&mut self, info: HostInfo) {
        self.inspect.update(&info);
        self.inner = info;
    }
}

pub struct HostInfoInspect {
    _inspect: inspect::Node,
    identifier: inspect::UintProperty,
    technology: inspect::StringProperty,
    active: inspect::UintProperty,
    discoverable: inspect::UintProperty,
    discovering: inspect::UintProperty,
}

impl HostInfoInspect {
    fn update(&mut self, info: &HostInfo) {
        self.identifier.set(info.id.0);
        self.technology.set(&info.technology.debug());
        self.active.set(info.active.to_property());
        self.discoverable.set(info.discoverable.to_property());
        self.discovering.set(info.discovering.to_property());
    }
}

impl IsInspectable for HostInfo {
    type I = HostInfoInspect;
}

impl InspectData<HostInfo> for HostInfoInspect {
    fn new(info: &HostInfo, inspect: inspect::Node) -> HostInfoInspect {
        HostInfoInspect {
            identifier: inspect.create_uint("identifier", info.id.0),
            technology: inspect.create_string("technology", info.technology.debug()),
            active: inspect.create_uint("active", info.active.to_property()),
            discoverable: inspect.create_uint("discoverable", info.discoverable.to_property()),
            discovering: inspect.create_uint("discovering", info.discovering.to_property()),
            _inspect: inspect,
        }
    }
}

/// Example Bluetooth host for testing.
pub fn example_host(id: HostId, active: bool, discoverable: bool) -> fsys::HostInfo {
    fsys::HostInfo {
        id: Some(id.into()),
        technology: Some(fsys::TechnologyType::LowEnergy),
        active: Some(active),
        local_name: Some("fuchsia123".to_string()),
        discoverable: Some(discoverable),
        discovering: Some(true),
        addresses: Some(vec![Address::Public([1, 2, 3, 4, 5, 6]).into()]),
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use {
        diagnostics_assertions::assert_data_tree, fidl_fuchsia_bluetooth as fbt,
        fuchsia_inspect as inspect,
    };

    #[test]
    fn from_fidl_id_not_present() {
        let info = HostInfo::try_from(fsys::HostInfo::default());
        assert!(info.is_err());
    }

    #[test]
    fn from_fidl_technology_not_present() {
        let info = fsys::HostInfo { id: Some(fbt::HostId { value: 1 }), ..Default::default() };
        let info = HostInfo::try_from(info);
        assert!(info.is_err());
    }

    #[test]
    fn from_fidl_addresses_not_present() {
        let info = fsys::HostInfo {
            id: Some(fbt::HostId { value: 1 }),
            technology: Some(fsys::TechnologyType::LowEnergy),
            ..Default::default()
        };
        let info = HostInfo::try_from(info);
        assert!(info.is_err());
    }

    #[test]
    fn from_fidl_addresses_is_empty() {
        let info = fsys::HostInfo {
            id: Some(fbt::HostId { value: 1 }),
            technology: Some(fsys::TechnologyType::LowEnergy),
            addresses: Some(vec![]),
            ..Default::default()
        };
        let info = HostInfo::try_from(info);
        assert!(info.is_err());
    }

    #[test]
    fn from_fidl_optional_fields_not_present() {
        let info = fsys::HostInfo {
            id: Some(fbt::HostId { value: 1 }),
            technology: Some(fsys::TechnologyType::LowEnergy),
            addresses: Some(vec![fbt::Address {
                type_: fbt::AddressType::Public,
                bytes: [1, 2, 3, 4, 5, 6],
            }]),
            ..Default::default()
        };
        let expected = HostInfo {
            id: HostId(1),
            technology: fsys::TechnologyType::LowEnergy,
            addresses: vec![Address::Public([1, 2, 3, 4, 5, 6])],
            active: false,
            local_name: None,
            discoverable: false,
            discovering: false,
        };

        let info = HostInfo::try_from(info).expect("expected successful conversion");
        assert_eq!(expected, info);
    }

    #[test]
    fn from_fidl_optional_fields_present() {
        let info = fsys::HostInfo {
            id: Some(fbt::HostId { value: 1 }),
            technology: Some(fsys::TechnologyType::LowEnergy),
            active: Some(true),
            local_name: Some("name".to_string()),
            discoverable: Some(false),
            discovering: Some(true),
            addresses: Some(vec![fbt::Address {
                type_: fbt::AddressType::Public,
                bytes: [1, 2, 3, 4, 5, 6],
            }]),
            ..Default::default()
        };
        let expected = HostInfo {
            id: HostId(1),
            technology: fsys::TechnologyType::LowEnergy,
            addresses: vec![Address::Public([1, 2, 3, 4, 5, 6])],
            active: true,
            local_name: Some("name".to_string()),
            discoverable: false,
            discovering: true,
        };

        let info = HostInfo::try_from(info).expect("expected successful conversion");
        assert_eq!(expected, info);
    }

    #[test]
    fn to_fidl() {
        let info = HostInfo {
            id: HostId(1),
            technology: fsys::TechnologyType::LowEnergy,
            addresses: vec![Address::Public([1, 2, 3, 4, 5, 6])],
            active: false,
            local_name: Some("name".to_string()),
            discoverable: false,
            discovering: false,
        };
        let expected = fsys::HostInfo {
            id: Some(fbt::HostId { value: 1 }),
            technology: Some(fsys::TechnologyType::LowEnergy),
            active: Some(false),
            local_name: Some("name".to_string()),
            discoverable: Some(false),
            discovering: Some(false),
            addresses: Some(vec![fbt::Address {
                type_: fbt::AddressType::Public,
                bytes: [1, 2, 3, 4, 5, 6],
            }]),
            ..Default::default()
        };

        assert_eq!(expected, info.into());
    }

    #[test]
    fn inspect() {
        let inspector = inspect::Inspector::default();
        let node = inspector.root().create_child("info");
        let info = HostInfo {
            id: HostId(1),
            technology: fsys::TechnologyType::LowEnergy,
            addresses: vec![Address::Public([1, 2, 3, 4, 5, 6])],
            active: false,
            local_name: Some("name".to_string()),
            discoverable: false,
            discovering: true,
        };
        let mut info = Inspectable::new(info, node);
        assert_data_tree!(inspector, root: {
            info: contains {
                identifier: 1u64,
                technology: "LowEnergy",
                active: 0u64,
                discoverable: 0u64,
                discovering: 1u64
            }
        });

        info.update(HostInfo {
            id: HostId(1),
            technology: fsys::TechnologyType::LowEnergy,
            addresses: vec![Address::Public([1, 2, 3, 4, 5, 6])],
            active: true,
            local_name: Some("foo".to_string()),
            discoverable: true,
            discovering: true,
        });
        assert_data_tree!(inspector, root: {
            info: contains {
                identifier: 1u64,
                technology: "LowEnergy",
                active: 1u64,
                discoverable: 1u64,
                discovering: 1u64
            }
        });
    }
}