esp32_nimble/
ble_security.rs

1use crate::enums;
2use esp_idf_svc::sys as esp_idf_sys;
3
4pub struct BLESecurity {
5    passkey: u32,
6}
7
8impl BLESecurity {
9    pub(crate) fn new() -> Self {
10        Self { passkey: 0 }
11    }
12
13    /// Set the authorization mode for this device.
14    pub fn set_auth(&mut self, auth_req: enums::AuthReq) -> &mut Self {
15        unsafe {
16            esp_idf_sys::ble_hs_cfg.set_sm_bonding(auth_req.contains(enums::AuthReq::Bond).into());
17            esp_idf_sys::ble_hs_cfg.set_sm_mitm(auth_req.contains(enums::AuthReq::Mitm).into());
18            esp_idf_sys::ble_hs_cfg.set_sm_sc(auth_req.contains(enums::AuthReq::Sc).into());
19        }
20
21        self
22    }
23
24    /// Get the current passkey used for pairing.
25    pub fn get_passkey(&self) -> u32 {
26        self.passkey
27    }
28
29    /// Set the passkey the server will ask for when pairing.
30    /// * The passkey will always be exactly 6 digits. Setting the passkey to 1234
31    ///   will require the user to provide '001234'
32    /// * a dynamic passkey can also be set by [`crate::BLEServer::on_passkey_request`]
33    pub fn set_passkey(&mut self, passkey: u32) -> &mut Self {
34        debug_assert!(
35            passkey <= 999999,
36            "passkey must be between 000000..=999999 inclusive"
37        );
38        self.passkey = passkey;
39        self
40    }
41
42    /// Set the Input/Output capabilities of this device.
43    pub fn set_io_cap(&mut self, iocap: enums::SecurityIOCap) -> &mut Self {
44        unsafe { esp_idf_sys::ble_hs_cfg.sm_io_cap = iocap.into() };
45        self
46    }
47
48    /// If we are the initiator of the security procedure this sets the keys we will distribute.
49    pub fn set_security_init_key(&mut self, init_key: enums::PairKeyDist) -> &mut Self {
50        unsafe { esp_idf_sys::ble_hs_cfg.sm_our_key_dist = init_key.bits() };
51        self
52    }
53
54    /// Set the keys we are willing to accept during pairing.
55    pub fn set_security_resp_key(&mut self, resp_key: enums::PairKeyDist) -> &mut Self {
56        unsafe { esp_idf_sys::ble_hs_cfg.sm_their_key_dist = resp_key.bits() };
57        self
58    }
59
60    /// Set up for pairing in RPA(Resolvable Private Address).
61    ///
62    /// ( see: <https://github.com/taks/esp32-nimble/issues/24> )
63    pub fn resolve_rpa(&mut self) -> &mut Self {
64        self.set_security_init_key(enums::PairKeyDist::ENC | enums::PairKeyDist::ID)
65            .set_security_resp_key(enums::PairKeyDist::ENC | enums::PairKeyDist::ID)
66    }
67}