Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / third_party / betocore / np_adv / src / shared_data.rs

shared_data.rs229 lines · 6.6 KiBRaw
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Data types shared between V0 and V1 advertisements
16
17use sink::Sink;
18use strum_macros::FromRepr;
19use tinyvec::ArrayVec;
20
21/// Power in dBm, calibrated as per
22/// [Eddystone](https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power)
23#[derive(Debug, PartialEq, Eq, Clone, Copy)]
24pub struct TxPower {
25 /// Power in `[-100, 20]`
26 power: i8,
27}
28
29impl TxPower {
30 /// Power in `[-100, 20]`
31 pub fn as_i8(&self) -> i8 {
32 self.power
33 }
34}
35
36impl TryFrom<i8> for TxPower {
37 type Error = TxPowerOutOfRange;
38
39 fn try_from(value: i8) -> Result<Self, Self::Error> {
40 if !(-100..=20).contains(&value) {
41 Err(TxPowerOutOfRange)
42 } else {
43 Ok(TxPower { power: value })
44 }
45 }
46}
47
48/// Tx power was out of the valid range `[-100, 20]`.
49#[derive(Debug, PartialEq, Eq)]
50pub struct TxPowerOutOfRange;
51
52/// MDP's context sync number, used to inform other devices that they have stale context.
53#[derive(Debug, PartialEq, Eq, Clone, Copy)]
54pub struct ContextSyncSeqNum {
55 /// 4-bit sequence
56 num: u8,
57}
58
59impl ContextSyncSeqNum {
60 /// Returns the context seq num as a u8
61 pub fn as_u8(&self) -> u8 {
62 self.num
63 }
64}
65
66impl TryFrom<u8> for ContextSyncSeqNum {
67 type Error = ContextSyncSeqNumOutOfRange;
68
69 fn try_from(value: u8) -> Result<Self, Self::Error> {
70 // must only have low nibble
71 if value > 0x0F {
72 Err(ContextSyncSeqNumOutOfRange)
73 } else {
74 Ok(ContextSyncSeqNum { num: value })
75 }
76 }
77}
78
79/// Seq num must be in `[0-15]`.
80#[derive(Debug, PartialEq, Eq)]
81pub struct ContextSyncSeqNumOutOfRange;
82
83/// A description of what kind of device is broadcasting.
84#[repr(u8)]
85#[derive(Clone, Copy, Debug, PartialEq, Eq, FromRepr, strum_macros::EnumIter)]
86pub enum DeviceType {
87 /// The type of device doing the broadcasting is completely unknown.
88 Unknown = 0,
89 /// The broadcasting device is a mobile phone.
90 Phone = 1,
91 /// The broadcasting device is a tablet.
92 Tablet = 2,
93 /// The broadcasting device is a (non-TV) display.
94 Display = 3,
95 /// The broadcasting device is a (non-CrOS) laptop.
96 Laptop = 4,
97 /// The broadcasting device is a TV.
98 TV = 5,
99 /// The broadcasting device is a watch.
100 Watch = 6,
101 /// The broadcasting device is a Chromebook.
102 ChromeOS = 7,
103 /// The broadcasting device is some kind of foldable.
104 Foldable = 8,
105 /// The broadcasting device is a car.
106 Automotive = 9,
107 /// The broadscasting device is a speaker.
108 Speaker = 10,
109}
110
111impl TryFrom<u8> for DeviceType {
112 type Error = ();
113
114 // We implement try_from to maintain the standard Rust idiom for fallible conversions.
115 // This is the expected API for any crate consuming DeviceType directly.
116 fn try_from(value: u8) -> Result<Self, Self::Error> {
117 DeviceType::from_repr(value).ok_or(())
118 }
119}
120
121/// The minimum length of a device name in a `DeviceInfo` data element.
122pub const MIN_DEVICE_NAME_LEN: usize = 5;
123/// The maximum length of a device name in a `DeviceInfo` data element.
124pub const MAX_DEVICE_NAME_LEN: usize = 9;
125
126/// Device information including a device type and a device name.
127#[derive(Debug, PartialEq, Eq, Clone)]
128pub struct DeviceInfo {
129 device_type: DeviceType,
130 name_truncated: bool,
131 device_name: ArrayVec<[u8; MAX_DEVICE_NAME_LEN]>,
132}
133
134impl DeviceInfo {
135 /// The device type.
136 pub fn device_type(&self) -> DeviceType {
137 self.device_type
138 }
139
140 /// Whether or not the device name was truncated.
141 pub fn name_truncated(&self) -> bool {
142 self.name_truncated
143 }
144
145 /// The device name.
146 pub fn device_name(&self) -> &[u8] {
147 &self.device_name
148 }
149}
150
151/// Errors that can occur when creating a `DeviceInfo`.
152#[derive(Debug, PartialEq, Eq)]
153pub enum DeviceInfoMalformed {
154 /// The device name is too short.
155 NameTooShort,
156 /// The device name is too long.
157 NameTooLong,
158}
159
160impl<'a> TryFrom<(DeviceType, bool, &'a [u8])> for DeviceInfo {
161 type Error = DeviceInfoMalformed;
162
163 fn try_from(
164 (device_type, name_truncated, device_name): (DeviceType, bool, &'a [u8]),
165 ) -> Result<Self, Self::Error> {
166 if device_name.len() < MIN_DEVICE_NAME_LEN {
167 Err(DeviceInfoMalformed::NameTooShort)
168 } else if device_name.len() > MAX_DEVICE_NAME_LEN {
169 Err(DeviceInfoMalformed::NameTooLong)
170 } else {
171 let mut array_vec = ArrayVec::new();
172 array_vec.try_extend_from_slice(device_name).ok_or(DeviceInfoMalformed::NameTooLong)?;
173 Ok(Self { device_type, name_truncated, device_name: array_vec })
174 }
175 }
176}
177
178#[allow(clippy::unwrap_used)]
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[test]
184 fn tx_power_out_of_range() {
185 assert_eq!(TxPowerOutOfRange, TxPower::try_from(-101).unwrap_err());
186 assert_eq!(TxPowerOutOfRange, TxPower::try_from(21).unwrap_err());
187 }
188
189 #[test]
190 fn tx_power_ok() {
191 assert_eq!(-100, TxPower::try_from(-100).unwrap().power);
192 assert_eq!(20, TxPower::try_from(20).unwrap().power);
193 }
194
195 #[test]
196 fn context_sync_seq_num_out_of_range() {
197 assert_eq!(ContextSyncSeqNumOutOfRange, ContextSyncSeqNum::try_from(0x10).unwrap_err());
198 }
199
200 #[test]
201 fn context_sync_seq_num_ok() {
202 assert_eq!(0x0F, ContextSyncSeqNum::try_from(0x0F).unwrap().num);
203 }
204
205 #[test]
206 fn device_info_name_too_short() {
207 assert_eq!(
208 DeviceInfoMalformed::NameTooShort,
209 DeviceInfo::try_from((DeviceType::Phone, false, "abcd".as_bytes())).unwrap_err()
210 );
211 }
212
213 #[test]
214 fn device_info_name_too_long() {
215 assert_eq!(
216 DeviceInfoMalformed::NameTooLong,
217 DeviceInfo::try_from((DeviceType::Phone, false, "0123456789".as_bytes())).unwrap_err()
218 );
219 }
220
221 #[test]
222 fn device_info_ok() {
223 let device_info =
224 DeviceInfo::try_from((DeviceType::Phone, true, "abcde".as_bytes())).unwrap();
225 assert_eq!(device_info.device_type(), DeviceType::Phone);
226 assert!(device_info.name_truncated());
227 assert_eq!(device_info.device_name(), "abcde".as_bytes());
228 }
229}