Skip to main content

qualia_core_db/net/acoustic_ble_mesh/
ble.rs

1//! BLE transport and BLE Mesh: nodes, addressing, capabilities, the mesh
2//! network/provisioning/configuration/security stack, advertiser, scanner,
3//! and connection management for short-range communication.
4
5use super::*;
6
7/// BLE network for short-range communication
8pub struct BleNetwork {
9    nodes: HashMap<String, BleNode>,
10    mesh_manager: BleMeshManager,
11    advertiser: BleAdvertiser,
12    scanner: BleScanner,
13    connection_manager: BleConnectionManager,
14}
15
16/// BLE node
17#[derive(Debug, Clone)]
18pub struct BleNode {
19    pub node_id: String,
20    pub address: BleAddress,
21    pub capabilities: BleCapabilities,
22    pub role: BleRole,
23    pub connection_state: ConnectionState,
24    pub rssi: i8,
25    pub battery_level: f64,
26}
27
28/// BLE address
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct BleAddress {
31    pub address: [u8; 6],
32    pub address_type: BleAddressType,
33}
34
35/// BLE address types
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum BleAddressType {
38    Public,
39    Random,
40    ResolvablePrivate,
41    NonResolvablePrivate,
42}
43
44/// BLE capabilities
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct BleCapabilities {
47    pub max_connections: u8,
48    pub data_length: u16,
49    pub phy_types: Vec<BlePhyType>,
50    pub features: Vec<BleFeature>,
51}
52
53/// BLE PHY types
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub enum BlePhyType {
56    LE1M,
57    LE2M,
58    LECoded,
59}
60
61/// BLE features
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub enum BleFeature {
64    ExtendedAdvertising,
65    LE2MPHY,
66    LEDataPacketLengthExtension,
67    LLPrivacy,
68    LEExtendedScannerFilterPolicies,
69}
70
71/// BLE roles
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub enum BleRole {
74    Peripheral,
75    Central,
76    Observer,
77    Broadcaster,
78}
79
80/// Connection states
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum ConnectionState {
83    Disconnected,
84    Connecting,
85    Connected,
86    Disconnecting,
87}
88
89/// BLE mesh manager
90pub struct BleMeshManager {
91    mesh_network: BleMeshNetwork,
92    provisioning_manager: ProvisioningManager,
93    configuration_manager: ConfigurationManager,
94    message_handler: MeshMessageHandler,
95}
96
97/// BLE mesh network
98#[derive(Debug, Clone)]
99pub struct BleMeshNetwork {
100    pub network_id: String,
101    pub network_key: [u8; 16],
102    pub iv_index: u32,
103    pub seq_num: u32,
104    pub nodes: HashMap<u16, MeshNode>,
105    pub elements: HashMap<u16, Vec<MeshElement>>,
106}
107
108/// Mesh node
109#[derive(Debug, Clone)]
110pub struct MeshNode {
111    pub unicast_address: u16,
112    pub device_key: [u8; 16],
113    pub composition_data: CompositionData,
114    pub default_ttl: u8,
115    pub features: NodeFeatures,
116}
117
118/// Composition data
119#[derive(Debug, Clone)]
120pub struct CompositionData {
121    pub cid: u16,
122    pub pid: u16,
123    pub vid: u16,
124    pub crpl: u16,
125    pub features: NodeFeatures,
126    pub elements: Vec<Element>,
127}
128
129/// Node features
130#[derive(Debug, Clone)]
131pub struct NodeFeatures {
132    pub relay: bool,
133    pub proxy: bool,
134    pub friend: bool,
135    pub low_power: bool,
136}
137
138/// Element
139#[derive(Debug, Clone)]
140pub struct Element {
141    pub location: u16,
142    pub sig_models: Vec<u16>,
143    pub vendor_models: Vec<u16>,
144}
145
146/// Mesh element
147#[derive(Debug, Clone)]
148pub struct MeshElement {
149    pub element_index: u8,
150    pub location: u16,
151    pub models: Vec<MeshModel>,
152}
153
154/// Mesh model
155#[derive(Debug, Clone)]
156pub struct MeshModel {
157    pub model_id: u16,
158    pub vendor_id: Option<u16>,
159    pub publication: Option<Publication>,
160    pub subscriptions: Vec<u16>,
161}
162
163/// Publication
164#[derive(Debug, Clone)]
165pub struct Publication {
166    pub address: u16,
167    pub app_key_index: u12,
168    pub credential_flag: bool,
169    pub ttl: u8,
170    pub period: u8,
171    pub retransmit: Retransmit,
172}
173
174/// Retransmit
175#[derive(Debug, Clone)]
176pub struct Retransmit {
177    pub count: u3,
178    pub interval: u5,
179}
180
181/// Provisioning manager
182pub struct ProvisioningManager {
183    provisioning_protocol: ProvisioningProtocol,
184    provisioning_data: ProvisioningData,
185    oob_data: Option<OobData>,
186}
187
188/// Provisioning protocols
189#[derive(Debug, Clone, PartialEq)]
190pub enum ProvisioningProtocol {
191    PBADV,
192    PBGATT,
193    PBNOOB,
194    PBALERT,
195}
196
197/// Provisioning data
198#[derive(Debug, Clone)]
199pub struct ProvisioningData {
200    pub network_key: [u8; 16],
201    pub net_key_index: u12,
202    pub flags: u8,
203    pub iv_index: u32,
204    pub unicast_address: u16,
205}
206
207/// OOB data
208#[derive(Debug, Clone)]
209pub struct OobData {
210    pub oob_type: OobType,
211    pub data: Vec<u8>,
212}
213
214/// OOB types
215#[derive(Debug, Clone, PartialEq)]
216pub enum OobType {
217    Static,
218    Output,
219    Input,
220    None,
221}
222
223/// Configuration manager
224pub struct ConfigurationManager {
225    config_database: ConfigDatabase,
226    config_models: Vec<ConfigModel>,
227    access_control: AccessControl,
228}
229
230/// Config database
231#[derive(Debug, Clone)]
232pub struct ConfigDatabase {
233    pub app_keys: HashMap<u12, AppKey>,
234    pub subnet_list: Vec<Subnet>,
235    pub virtual_addresses: HashMap<u16, VirtualAddress>,
236}
237
238/// App key
239#[derive(Debug, Clone)]
240pub struct AppKey {
241    pub key: [u8; 16],
242    pub net_key_index: u12,
243    pub aid: u4,
244}
245
246/// Subnet
247#[derive(Debug, Clone)]
248pub struct Subnet {
249    pub net_key_index: u12,
250    pub app_key_indices: Vec<u12>,
251    pub kr_flag: bool,
252    pub phase: u8,
253}
254
255/// Virtual address
256#[derive(Debug, Clone)]
257pub struct VirtualAddress {
258    pub address: u16,
259    pub label_uuid: [u8; 16],
260}
261
262/// Config model
263#[derive(Debug, Clone)]
264pub struct ConfigModel {
265    pub model_id: u16,
266    pub opcode: u16,
267    pub parameters: Vec<ConfigParameter>,
268}
269
270/// Config parameter
271#[derive(Debug, Clone)]
272pub struct ConfigParameter {
273    pub name: String,
274    pub value: ConfigValue,
275}
276
277/// Config values
278#[derive(Debug, Clone)]
279pub enum ConfigValue {
280    U8(u8),
281    U16(u16),
282    U32(u32),
283    Buffer(Vec<u8>),
284}
285
286/// Access control
287#[derive(Debug, Clone)]
288pub struct AccessControl {
289    pub access_list: Vec<AccessEntry>,
290    pub default_policy: AccessPolicy,
291}
292
293/// Access entry
294#[derive(Debug, Clone)]
295pub struct AccessEntry {
296    pub address: u16,
297    pub permissions: Vec<Permission>,
298}
299
300/// Permissions
301#[derive(Debug, Clone, PartialEq)]
302pub enum Permission {
303    Read,
304    Write,
305    Subscribe,
306    Publish,
307    Admin,
308}
309
310/// Access policies
311#[derive(Debug, Clone, PartialEq)]
312pub enum AccessPolicy {
313    Allow,
314    Deny,
315    RequireAuth,
316}
317
318/// Mesh message handler
319pub struct MeshMessageHandler {
320    message_queue: Vec<MeshMessage>,
321    routing_table: RoutingTable,
322    security_manager: MeshSecurityManager,
323}
324
325/// Mesh message
326#[derive(Debug, Clone)]
327pub struct MeshMessage {
328    pub message_id: String,
329    pub source: u16,
330    pub destination: u16,
331    pub ttl: u8,
332    pub opcode: u16,
333    pub parameters: Vec<u8>,
334    pub app_key_index: u12,
335    pub net_key_index: u12,
336    pub sequence_number: u32,
337    pub timestamp: Instant,
338}
339
340/// Mesh security manager
341pub struct MeshSecurityManager {
342    pub network_keys: HashMap<u12, [u8; 16]>,
343    pub application_keys: HashMap<u12, [u8; 16]>,
344    pub device_keys: HashMap<u16, [u8; 16]>,
345    pub beacon_key: [u8; 16],
346}
347
348/// BLE advertiser
349pub struct BleAdvertiser {
350    advertising_data: Vec<u8>,
351    scan_response_data: Vec<u8>,
352    advertising_parameters: AdvertisingParameters,
353    active_advertisements: Vec<ActiveAdvertisement>,
354}
355
356/// Advertising parameters
357#[derive(Debug, Clone)]
358pub struct AdvertisingParameters {
359    pub interval_min: u16,
360    pub interval_max: u16,
361    pub type_: AdvertisingType,
362    pub filter_policy: AdvertisingFilterPolicy,
363}
364
365/// Advertising types
366#[derive(Debug, Clone, PartialEq)]
367pub enum AdvertisingType {
368    ConnectableUndirected,
369    ConnectableDirected,
370    ScannableUndirected,
371    NonConnectableUndirected,
372}
373
374/// Advertising filter policies
375#[derive(Debug, Clone, PartialEq)]
376pub enum AdvertisingFilterPolicy {
377    AllowScanAny,
378    AllowScanWhitelist,
379    AllowConnectAny,
380    AllowConnectWhitelist,
381}
382
383/// Active advertisement
384#[derive(Debug, Clone)]
385pub struct ActiveAdvertisement {
386    pub handle: u8,
387    pub parameters: AdvertisingParameters,
388    pub data: Vec<u8>,
389    pub status: AdvertisementStatus,
390}
391
392/// Advertisement status
393#[derive(Debug, Clone, PartialEq)]
394pub enum AdvertisementStatus {
395    Active,
396    Paused,
397    Stopped,
398    Error,
399}
400
401/// BLE scanner
402pub struct BleScanner {
403    scanning_parameters: ScanningParameters,
404    scan_filter: ScanFilter,
405    active_scans: Vec<ActiveScan>,
406}
407
408/// Scanning parameters
409#[derive(Debug, Clone)]
410pub struct ScanningParameters {
411    pub interval: u16,
412    pub window: u16,
413    pub type_: ScanningType,
414    pub filter_duplicates: bool,
415}
416
417/// Scanning types
418#[derive(Debug, Clone, PartialEq)]
419pub enum ScanningType {
420    Passive,
421    Active,
422}
423
424/// Scan filter
425#[derive(Debug, Clone)]
426pub struct ScanFilter {
427    pub address_filter: Option<BleAddress>,
428    pub rssi_filter: Option<i8>,
429    pub service_uuid_filter: Vec<u16>,
430}
431
432/// Active scan
433#[derive(Debug, Clone)]
434pub struct ActiveScan {
435    pub handle: u8,
436    pub parameters: ScanningParameters,
437    pub results: Vec<ScanResult>,
438    pub status: ScanStatus,
439}
440
441/// Scan result
442#[derive(Debug, Clone)]
443pub struct ScanResult {
444    pub address: BleAddress,
445    pub rssi: i8,
446    pub advertising_data: Vec<u8>,
447    pub scan_response_data: Vec<u8>,
448    pub timestamp: Instant,
449}
450
451/// Scan status
452#[derive(Debug, Clone, PartialEq)]
453pub enum ScanStatus {
454    Scanning,
455    Paused,
456    Stopped,
457    Error,
458}
459
460/// BLE connection manager
461pub struct BleConnectionManager {
462    connections: HashMap<u16, BleConnection>,
463    connection_parameters: ConnectionParameters,
464    security_manager: BleSecurityManager,
465}
466
467/// BLE connection
468#[derive(Debug, Clone)]
469pub struct BleConnection {
470    pub handle: u16,
471    pub role: BleRole,
472    pub address: BleAddress,
473    pub parameters: ConnectionParameters,
474    pub state: ConnectionState,
475    pub security_level: SecurityLevel,
476    pub mtu: u16,
477    pub data_length: u16,
478}
479
480/// Connection parameters
481#[derive(Debug, Clone)]
482pub struct ConnectionParameters {
483    pub min_interval: u16,
484    pub max_interval: u16,
485    pub latency: u16,
486    pub supervision_timeout: u16,
487    pub min_ce_length: u16,
488    pub max_ce_length: u16,
489}
490
491/// Security levels
492#[derive(Debug, Clone, PartialEq)]
493pub enum SecurityLevel {
494    None,
495    Low,
496    Medium,
497    High,
498    FIPS,
499}
500
501/// BLE security manager
502pub struct BleSecurityManager {
503    pub encryption_keys: HashMap<u16, EncryptionKey>,
504    pub identity_keys: HashMap<u16, IdentityKey>,
505    pub signing_keys: HashMap<u16, SigningKey>,
506    pub csrk: HashMap<u16, Csrk>,
507}
508
509/// Encryption key
510#[derive(Debug, Clone)]
511pub struct EncryptionKey {
512    pub ltk: [u8; 16],
513    pub rand: [u8; 8],
514    pub ediv: u16,
515}
516
517/// Identity key
518#[derive(Debug, Clone)]
519pub struct IdentityKey {
520    pub irk: [u8; 16],
521    pub address: BleAddress,
522}
523
524/// Signing key
525#[derive(Debug, Clone)]
526pub struct SigningKey {
527    pub csrk: [u8; 16],
528    pub counter: u32,
529}
530
531/// CSRK
532#[derive(Debug, Clone)]
533pub struct Csrk {
534    pub key: [u8; 16],
535    pub counter: u32,
536}
537
538impl BleNetwork {
539    /// Create the BLE network facade with uninitialised sub-managers.
540    pub fn new() -> Self {
541        Self {
542            nodes: HashMap::new(),
543            mesh_manager: BleMeshManager::new(),
544            advertiser: BleAdvertiser::new(),
545            scanner: BleScanner::new(),
546            connection_manager: BleConnectionManager::new(),
547        }
548    }
549
550    /// Register a BLE node in the node registry.
551    pub fn register_node(&mut self, node: BleNode) {
552        self.nodes.insert(node.node_id.clone(), node);
553    }
554
555    /// Initialise mesh manager, advertiser, scanner, and connection manager in order.
556    pub fn initialize(&mut self) -> Result<(), MeshError> {
557        // Initialize BLE network components
558        self.mesh_manager.initialize()?;
559        self.advertiser.initialize()?;
560        self.scanner.initialize()?;
561        self.connection_manager.initialize()?;
562
563        // Register default local BLE node interface if none registered
564        if self.nodes.is_empty() {
565            let local_node = BleNode {
566                node_id: "ble_local_gateway".to_string(),
567                address: BleAddress {
568                    address: [0x00, 0x1A, 0x7D, 0xDA, 0x71, 0x13],
569                    address_type: BleAddressType::Public,
570                },
571                capabilities: BleCapabilities {
572                    max_connections: 8,
573                    data_length: 251,
574                    phy_types: vec![BlePhyType::LE1M, BlePhyType::LE2M, BlePhyType::LECoded],
575                    features: vec![
576                        BleFeature::ExtendedAdvertising,
577                        BleFeature::LE2MPHY,
578                        BleFeature::LEDataPacketLengthExtension,
579                    ],
580                },
581                role: BleRole::Central,
582                connection_state: ConnectionState::Connected,
583                rssi: -45,
584                battery_level: 100.0,
585            };
586            self.nodes.insert(local_node.node_id.clone(), local_node);
587        }
588        Ok(())
589    }
590
591    /// Discover nearby nodes from the active node registry and scan results.
592    pub fn discover_nodes(&mut self) -> Result<Vec<BleNode>, MeshError> {
593        let mut discovered: Vec<BleNode> = self.nodes.values().cloned().collect();
594
595        // Process any scan results from active scans into nodes
596        for scan in &self.scanner.active_scans {
597            for res in &scan.results {
598                let node_id = format!(
599                    "ble_{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
600                    res.address.address[0],
601                    res.address.address[1],
602                    res.address.address[2],
603                    res.address.address[3],
604                    res.address.address[4],
605                    res.address.address[5],
606                );
607                if !self.nodes.contains_key(&node_id) {
608                    let node = BleNode {
609                        node_id: node_id.clone(),
610                        address: res.address.clone(),
611                        capabilities: BleCapabilities {
612                            max_connections: 3,
613                            data_length: 251,
614                            phy_types: vec![BlePhyType::LE1M],
615                            features: vec![BleFeature::ExtendedAdvertising],
616                        },
617                        role: BleRole::Peripheral,
618                        connection_state: ConnectionState::Disconnected,
619                        rssi: res.rssi,
620                        battery_level: 100.0,
621                    };
622                    self.nodes.insert(node_id, node.clone());
623                    discovered.push(node);
624                }
625            }
626        }
627
628        Ok(discovered)
629    }
630
631    /// Enqueue a message for BLE mesh delivery via the mesh message handler.
632    pub fn send_message(&mut self, message: &StoredMessage) -> Result<(), MeshError> {
633        let dest_hash = q_hash(&message.destination);
634        let src_hash = q_hash(&message.source);
635        let mesh_msg = MeshMessage {
636            message_id: message.message_id.clone(),
637            source: src_hash as u16,
638            destination: dest_hash as u16,
639            ttl: (message.ttl.as_secs().min(255)) as u8,
640            opcode: 0x01,
641            parameters: message.payload.clone(),
642            app_key_index: 0,
643            net_key_index: 0,
644            sequence_number: self.mesh_manager.mesh_network.seq_num,
645            timestamp: Instant::now(),
646        };
647        self.mesh_manager.mesh_network.seq_num = self.mesh_manager.mesh_network.seq_num.wrapping_add(1);
648        self.mesh_manager.message_handler.enqueue_message(mesh_msg);
649        Ok(())
650    }
651
652    /// Enqueue a raw payload for transmission to a destination via the BLE mesh message handler.
653    pub fn send_payload(
654        &mut self,
655        destination: &str,
656        payload: &[u8],
657        _priority: MessagePriority,
658    ) -> Result<(), MeshError> {
659        let dest_hash = q_hash(destination);
660        let mesh_msg = MeshMessage {
661            message_id: format!("payload_{}", self.mesh_manager.mesh_network.seq_num),
662            source: 0x0001,
663            destination: dest_hash as u16,
664            ttl: 64,
665            opcode: 0x02,
666            parameters: payload.to_vec(),
667            app_key_index: 0,
668            net_key_index: 0,
669            sequence_number: self.mesh_manager.mesh_network.seq_num,
670            timestamp: Instant::now(),
671        };
672        self.mesh_manager.mesh_network.seq_num = self.mesh_manager.mesh_network.seq_num.wrapping_add(1);
673        self.mesh_manager.message_handler.enqueue_message(mesh_msg);
674        Ok(())
675    }
676
677    /// Number of nodes currently registered in `self.nodes`.
678    pub fn get_node_count(&self) -> u32 {
679        self.nodes.len() as u32
680    }
681
682    /// Optimize BLE discovery scanning window and interval.
683    pub fn optimize_discovery(&mut self) -> Result<(), MeshError> {
684        self.scanner.scanning_parameters.interval = 160;
685        self.scanner.scanning_parameters.window = 80;
686        Ok(())
687    }
688}
689
690impl BleMeshManager {
691    /// Create a default `BleMeshManager`.
692    pub fn new() -> Self {
693        Self {
694            mesh_network: BleMeshNetwork::new(),
695            provisioning_manager: ProvisioningManager::new(),
696            configuration_manager: ConfigurationManager::new(),
697            message_handler: MeshMessageHandler::new(),
698        }
699    }
700
701    /// Initialise the `BleMeshManager` sub-components; propagates `MeshError`.
702    pub fn initialize(&mut self) -> Result<(), MeshError> {
703        self.provisioning_manager.initialize()?;
704        self.configuration_manager.initialize()?;
705        Ok(())
706    }
707
708    /// Borrow the mesh network state.
709    pub fn mesh_network(&self) -> &BleMeshNetwork {
710        &self.mesh_network
711    }
712
713    /// Mutable borrow of the mesh network state.
714    pub fn mesh_network_mut(&mut self) -> &mut BleMeshNetwork {
715        &mut self.mesh_network
716    }
717
718    /// Borrow the provisioning manager.
719    pub fn provisioning_manager(&self) -> &ProvisioningManager {
720        &self.provisioning_manager
721    }
722
723    /// Borrow the configuration manager.
724    pub fn configuration_manager(&self) -> &ConfigurationManager {
725        &self.configuration_manager
726    }
727
728    /// Borrow the mesh message handler.
729    pub fn message_handler(&self) -> &MeshMessageHandler {
730        &self.message_handler
731    }
732}
733
734impl BleMeshNetwork {
735    /// Create a default `BleMeshNetwork`.
736    pub fn new() -> Self {
737        Self {
738            network_id: "mesh_network_1".to_string(),
739            network_key: [0u8; 16],
740            iv_index: 0,
741            seq_num: 0,
742            nodes: HashMap::new(),
743            elements: HashMap::new(),
744        }
745    }
746}
747
748impl ProvisioningManager {
749    /// Create a default `ProvisioningManager`.
750    pub fn new() -> Self {
751        Self {
752            provisioning_protocol: ProvisioningProtocol::PBADV,
753            provisioning_data: ProvisioningData {
754                network_key: [0u8; 16],
755                net_key_index: 0,
756                flags: 0,
757                iv_index: 0,
758                unicast_address: 0x0001,
759            },
760            oob_data: None,
761        }
762    }
763
764    /// Initialise the `ProvisioningManager` sub-components; propagates `MeshError`.
765    pub fn initialize(&mut self) -> Result<(), MeshError> {
766        Ok(())
767    }
768
769    /// Borrow the provisioning protocol state machine.
770    pub fn protocol(&self) -> &ProvisioningProtocol {
771        &self.provisioning_protocol
772    }
773
774    /// Borrow the accumulated provisioning data.
775    pub fn provisioning_data(&self) -> &ProvisioningData {
776        &self.provisioning_data
777    }
778
779    /// Install out-of-band provisioning data.
780    pub fn set_oob_data(&mut self, data: OobData) {
781        self.oob_data = Some(data);
782    }
783
784    /// The out-of-band provisioning data, if provisioned.
785    pub fn oob_data(&self) -> Option<&OobData> {
786        self.oob_data.as_ref()
787    }
788}
789
790impl ConfigurationManager {
791    /// Create a default `ConfigurationManager`.
792    pub fn new() -> Self {
793        Self {
794            config_database: ConfigDatabase::new(),
795            config_models: Vec::new(),
796            access_control: AccessControl::new(),
797        }
798    }
799
800    /// Initialise the `ConfigurationManager` sub-components; propagates `MeshError`.
801    pub fn initialize(&mut self) -> Result<(), MeshError> {
802        Ok(())
803    }
804
805    /// Borrow the node configuration database.
806    pub fn config_database(&self) -> &ConfigDatabase {
807        &self.config_database
808    }
809
810    /// Mutable borrow of the node configuration database.
811    pub fn config_database_mut(&mut self) -> &mut ConfigDatabase {
812        &mut self.config_database
813    }
814
815    /// Register a `ConfigModel` in the database.
816    pub fn add_config_model(&mut self, model: ConfigModel) {
817        self.config_models.push(model);
818    }
819
820    /// The registered `ConfigModel`s.
821    pub fn config_models(&self) -> &[ConfigModel] {
822        &self.config_models
823    }
824
825    /// Borrow the configuration access-control list.
826    pub fn access_control(&self) -> &AccessControl {
827        &self.access_control
828    }
829}
830
831impl ConfigDatabase {
832    /// Create a default `ConfigDatabase`.
833    pub fn new() -> Self {
834        Self {
835            app_keys: HashMap::new(),
836            subnet_list: Vec::new(),
837            virtual_addresses: HashMap::new(),
838        }
839    }
840}
841
842impl AccessControl {
843    /// Create a default `AccessControl`.
844    pub fn new() -> Self {
845        Self {
846            access_list: Vec::new(),
847            default_policy: AccessPolicy::Allow,
848        }
849    }
850}
851
852impl MeshMessageHandler {
853    /// Create a default `MeshMessageHandler`.
854    pub fn new() -> Self {
855        Self {
856            message_queue: Vec::new(),
857            routing_table: RoutingTable::new(),
858            security_manager: MeshSecurityManager::new(),
859        }
860    }
861
862    /// Push `message` onto the mesh message queue.
863    pub fn enqueue_message(&mut self, message: MeshMessage) {
864        self.message_queue.push(message);
865    }
866
867    /// Pop the oldest queued `MeshMessage`, or `None` when empty.
868    pub fn dequeue_message(&mut self) -> Option<MeshMessage> {
869        self.message_queue.pop()
870    }
871
872    /// Current message-queue depth.
873    pub fn queue_length(&self) -> usize {
874        self.message_queue.len()
875    }
876
877    /// Borrow the mesh routing table.
878    pub fn routing_table(&self) -> &RoutingTable {
879        &self.routing_table
880    }
881
882    /// Borrow the mesh security manager.
883    pub fn security_manager(&self) -> &MeshSecurityManager {
884        &self.security_manager
885    }
886}
887
888impl MeshSecurityManager {
889    /// Create a default `MeshSecurityManager`.
890    pub fn new() -> Self {
891        Self {
892            network_keys: HashMap::new(),
893            application_keys: HashMap::new(),
894            device_keys: HashMap::new(),
895            beacon_key: [0u8; 16],
896        }
897    }
898}
899
900impl BleAdvertiser {
901    /// Create a default `BleAdvertiser`.
902    pub fn new() -> Self {
903        Self {
904            advertising_data: Vec::new(),
905            scan_response_data: Vec::new(),
906            advertising_parameters: AdvertisingParameters {
907                interval_min: 100,
908                interval_max: 200,
909                type_: AdvertisingType::ConnectableUndirected,
910                filter_policy: AdvertisingFilterPolicy::AllowScanAny,
911            },
912            active_advertisements: Vec::new(),
913        }
914    }
915
916    /// Initialise the `BleAdvertiser` sub-components; propagates `MeshError`.
917    pub fn initialize(&mut self) -> Result<(), MeshError> {
918        Ok(())
919    }
920
921    /// Set the advertising payload bytes.
922    pub fn set_advertising_data(&mut self, data: Vec<u8>) {
923        self.advertising_data = data;
924    }
925
926    /// The configured advertising payload bytes.
927    pub fn advertising_data(&self) -> &[u8] {
928        &self.advertising_data
929    }
930
931    /// Set the scan-response payload bytes.
932    pub fn set_scan_response_data(&mut self, data: Vec<u8>) {
933        self.scan_response_data = data;
934    }
935
936    /// The configured scan-response payload bytes.
937    pub fn scan_response_data(&self) -> &[u8] {
938        &self.scan_response_data
939    }
940
941    /// The active advertising parameters.
942    pub fn advertising_parameters(&self) -> &AdvertisingParameters {
943        &self.advertising_parameters
944    }
945
946    /// Borrow the `start_advertising` component.
947    pub fn start_advertising(&mut self, adv: ActiveAdvertisement) {
948        self.active_advertisements.push(adv);
949    }
950
951    /// Borrow the `stop_advertising` component.
952    pub fn stop_advertising(&mut self, handle: u8) {
953        self.active_advertisements.retain(|a| a.handle != handle);
954    }
955
956    /// Number of `active_advertisement` entries currently held.
957    pub fn active_advertisement_count(&self) -> usize {
958        self.active_advertisements.len()
959    }
960}
961
962impl BleScanner {
963    /// Create a default `BleScanner`.
964    pub fn new() -> Self {
965        Self {
966            scanning_parameters: ScanningParameters {
967                interval: 100,
968                window: 50,
969                type_: ScanningType::Active,
970                filter_duplicates: true,
971            },
972            scan_filter: ScanFilter {
973                address_filter: None,
974                rssi_filter: None,
975                service_uuid_filter: Vec::new(),
976            },
977            active_scans: Vec::new(),
978        }
979    }
980
981    /// Initialise the `BleScanner` sub-components; propagates `MeshError`.
982    pub fn initialize(&mut self) -> Result<(), MeshError> {
983        Ok(())
984    }
985
986    /// The active scanning parameters.
987    pub fn scanning_parameters(&self) -> &ScanningParameters {
988        &self.scanning_parameters
989    }
990
991    /// The active scan filter.
992    pub fn scan_filter(&self) -> &ScanFilter {
993        &self.scan_filter
994    }
995
996    /// Add a 16-bit service UUID to the scan filter.
997    pub fn add_service_uuid_filter(&mut self, uuid: u16) {
998        self.scan_filter.service_uuid_filter.push(uuid);
999    }
1000
1001    /// Borrow the `start_scan` component.
1002    pub fn start_scan(&mut self, scan: ActiveScan) {
1003        self.active_scans.push(scan);
1004    }
1005
1006    /// Borrow the `stop_scan` component.
1007    pub fn stop_scan(&mut self, handle: u8) {
1008        self.active_scans.retain(|s| s.handle != handle);
1009    }
1010
1011    /// Number of `active_scan` entries currently held.
1012    pub fn active_scan_count(&self) -> usize {
1013        self.active_scans.len()
1014    }
1015}
1016
1017impl BleConnectionManager {
1018    /// Create a default `BleConnectionManager`.
1019    pub fn new() -> Self {
1020        Self {
1021            connections: HashMap::new(),
1022            connection_parameters: ConnectionParameters {
1023                min_interval: 24,
1024                max_interval: 40,
1025                latency: 0,
1026                supervision_timeout: 700,
1027                min_ce_length: 0,
1028                max_ce_length: 0,
1029            },
1030            security_manager: BleSecurityManager::new(),
1031        }
1032    }
1033
1034    /// Initialise the `BleConnectionManager` sub-components; propagates `MeshError`.
1035    pub fn initialize(&mut self) -> Result<(), MeshError> {
1036        Ok(())
1037    }
1038
1039    /// Track `connection` under `handle`.
1040    pub fn add_connection(&mut self, handle: u16, connection: BleConnection) {
1041        self.connections.insert(handle, connection);
1042    }
1043
1044    /// Drop the connection tracked under `handle`.
1045    pub fn remove_connection(&mut self, handle: u16) {
1046        self.connections.remove(&handle);
1047    }
1048
1049    /// Number of `connection` entries currently held.
1050    pub fn connection_count(&self) -> usize {
1051        self.connections.len()
1052    }
1053
1054    /// Borrow the `connection`.
1055    pub fn get_connection(&self, handle: u16) -> Option<&BleConnection> {
1056        self.connections.get(&handle)
1057    }
1058
1059    /// The configured connection parameters.
1060    pub fn connection_parameters(&self) -> &ConnectionParameters {
1061        &self.connection_parameters
1062    }
1063
1064    /// Borrow the mesh security manager.
1065    pub fn security_manager(&self) -> &BleSecurityManager {
1066        &self.security_manager
1067    }
1068}
1069
1070impl BleSecurityManager {
1071    /// Create a default `BleSecurityManager`.
1072    pub fn new() -> Self {
1073        Self {
1074            encryption_keys: HashMap::new(),
1075            identity_keys: HashMap::new(),
1076            signing_keys: HashMap::new(),
1077            csrk: HashMap::new(),
1078        }
1079    }
1080}