Skip to main content

qualia_core_db/net/acoustic_ble_mesh/
acoustic.rs

1//! Acoustic network: nodes, channels, modem/PHY, and the acoustic protocol stack
2//! (physical / data-link / network / transport layers) for through-wall and
3//! underwater communication.
4
5use super::*;
6
7/// Acoustic network for underwater/through-wall communication
8pub struct AcousticNetwork {
9    nodes: HashMap<String, AcousticNode>,
10    channel_manager: AcousticChannelManager,
11    modem_controller: AcousticModemController,
12    protocol_handler: AcousticProtocolHandler,
13    tx_queue: Vec<StoredMessage>,
14}
15
16/// Acoustic node in the network
17#[derive(Debug, Clone)]
18pub struct AcousticNode {
19    pub node_id: String,
20    pub node_type: NodeType,
21    pub capabilities: AcousticCapabilities,
22    pub location: Option<Location>,
23    pub status: NodeStatus,
24    pub signal_strength: f64,
25    pub battery_level: f64,
26}
27
28/// Acoustic capabilities
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct AcousticCapabilities {
31    pub frequency_range: (f64, f64), // Hz
32    pub bandwidth: f64,              // Hz
33    pub max_range: f64,              // meters
34    pub data_rate: f64,              // bps
35    pub modulation: ModulationType,
36    pub error_correction: ErrorCorrectionType,
37}
38
39/// Modulation types
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub enum ModulationType {
42    FSK,
43    PSK,
44    OFDM,
45    DSSS,
46    Chirp,
47}
48
49/// Error correction types
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub enum ErrorCorrectionType {
52    None,
53    Hamming,
54    ReedSolomon,
55    Convolutional,
56    LDPC,
57}
58
59/// Node status
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub enum NodeStatus {
62    Active,
63    Idle,
64    Sleeping,
65    Error,
66    Offline,
67}
68
69/// Acoustic channel manager
70pub struct AcousticChannelManager {
71    available_channels: Vec<AcousticChannel>,
72    active_channels: HashMap<String, AcousticChannel>,
73    channel_allocation: ChannelAllocationStrategy,
74}
75
76/// Acoustic channel
77#[derive(Debug, Clone)]
78pub struct AcousticChannel {
79    pub channel_id: String,
80    pub frequency: f64,
81    pub bandwidth: f64,
82    pub power_level: f64,
83    pub modulation: ModulationType,
84    pub noise_floor: f64,
85    pub interference_level: f64,
86}
87
88/// Channel allocation strategies
89#[derive(Debug, Clone, PartialEq)]
90pub enum ChannelAllocationStrategy {
91    Fixed,
92    Dynamic,
93    Adaptive,
94    Opportunistic,
95}
96
97/// Acoustic modem controller
98pub struct AcousticModemController {
99    modem_type: ModemType,
100    transmission_power: f64,
101    receiver_sensitivity: f64,
102    signal_processing: SignalProcessingConfig,
103}
104
105/// Modem types
106#[derive(Debug, Clone, PartialEq)]
107pub enum ModemType {
108    SoftwareDefined,
109    HardwareBased,
110    Hybrid,
111}
112
113/// Signal processing configuration
114#[derive(Debug, Clone)]
115pub struct SignalProcessingConfig {
116    pub sampling_rate: f64,
117    pub fft_size: usize,
118    pub filter_type: FilterType,
119    pub noise_reduction: bool,
120    pub equalization: bool,
121}
122
123/// Filter types
124#[derive(Debug, Clone, PartialEq)]
125pub enum FilterType {
126    LowPass,
127    HighPass,
128    BandPass,
129    Notch,
130    Adaptive,
131}
132
133/// Packet handler
134pub struct PacketHandler {}
135
136/// Flow control
137pub struct FlowControl {}
138
139/// Error handling
140pub struct ErrorHandling {}
141
142/// Acoustic protocol handler
143pub struct AcousticProtocolHandler {
144    protocol_stack: AcousticProtocolStack,
145    packet_handler: PacketHandler,
146    flow_control: FlowControl,
147    error_handling: ErrorHandling,
148}
149
150/// Acoustic protocol stack
151#[derive(Debug, Clone)]
152pub struct AcousticProtocolStack {
153    pub physical_layer: PhysicalLayer,
154    pub data_link_layer: DataLinkLayer,
155    pub network_layer: NetworkLayer,
156    pub transport_layer: TransportLayer,
157}
158
159/// Physical layer
160#[derive(Debug, Clone)]
161pub struct PhysicalLayer {
162    pub modulation: ModulationType,
163    pub coding: ErrorCorrectionType,
164    pub frequency_hopping: bool,
165    pub power_control: bool,
166}
167
168/// Data link layer
169#[derive(Debug, Clone)]
170pub struct DataLinkLayer {
171    pub mac_protocol: MacProtocol,
172    pub frame_format: FrameFormat,
173    pub error_detection: ErrorDetection,
174    pub retransmission: RetransmissionStrategy,
175}
176
177/// MAC protocols
178#[derive(Debug, Clone, PartialEq)]
179pub enum MacProtocol {
180    CSMA,
181    TDMA,
182    FDMA,
183    CDMA,
184    Hybrid,
185}
186
187/// Frame formats
188#[derive(Debug, Clone, PartialEq)]
189pub enum FrameFormat {
190    Fixed,
191    Variable,
192    Adaptive,
193}
194
195/// Error detection
196#[derive(Debug, Clone, PartialEq)]
197pub enum ErrorDetection {
198    CRC,
199    Checksum,
200    Parity,
201    None,
202}
203
204/// Retransmission strategies
205#[derive(Debug, Clone, PartialEq)]
206pub enum RetransmissionStrategy {
207    StopAndWait,
208    GoBackN,
209    SelectiveRepeat,
210    Adaptive,
211}
212
213/// Network layer
214#[derive(Debug, Clone)]
215pub struct NetworkLayer {
216    pub routing_protocol: RoutingProtocol,
217    pub addressing_scheme: AddressingScheme,
218    pub fragmentation: bool,
219    pub congestion_control: bool,
220}
221
222/// Routing protocols
223#[derive(Debug, Clone, PartialEq)]
224pub enum RoutingProtocol {
225    Flooding,
226    DistanceVector,
227    LinkState,
228    Geographic,
229    Opportunistic,
230}
231
232/// Addressing schemes
233#[derive(Debug, Clone, PartialEq)]
234pub enum AddressingScheme {
235    Hierarchical,
236    Flat,
237    Geographic,
238    ContentBased,
239}
240
241/// Transport layer
242#[derive(Debug, Clone)]
243pub struct TransportLayer {
244    pub transport_protocol: TransportProtocol,
245    pub reliability: ReliabilityLevel,
246    pub flow_control: FlowControlType,
247    pub congestion_control: CongestionControlType,
248}
249
250/// Transport protocols
251#[derive(Debug, Clone, PartialEq)]
252pub enum TransportProtocol {
253    UDP,
254    TCP,
255    DTN,
256    Custom,
257}
258
259/// Reliability levels
260#[derive(Debug, Clone, PartialEq)]
261pub enum ReliabilityLevel {
262    BestEffort,
263    Reliable,
264    SemiReliable,
265    Adaptive,
266}
267
268/// Flow control types
269#[derive(Debug, Clone, PartialEq)]
270pub enum FlowControlType {
271    None,
272    WindowBased,
273    RateBased,
274    CreditBased,
275}
276
277/// Congestion control types
278#[derive(Debug, Clone, PartialEq)]
279pub enum CongestionControlType {
280    None,
281    AIMD,
282    RED,
283    Custom,
284}
285
286impl AcousticNetwork {
287    /// Construct a `AcousticNetwork` with default field values.
288    pub fn new() -> Self {
289        Self {
290            nodes: HashMap::new(),
291            channel_manager: AcousticChannelManager::new(),
292            modem_controller: AcousticModemController::new(),
293            protocol_handler: AcousticProtocolHandler::new(),
294            tx_queue: Vec::new(),
295        }
296    }
297
298    /// Register an acoustic node in the node registry.
299    pub fn register_node(&mut self, node: AcousticNode) {
300        self.nodes.insert(node.node_id.clone(), node);
301    }
302
303    /// Initialize channel manager, modem controller, and protocol handler.
304    pub fn initialize(&mut self) -> Result<(), MeshError> {
305        // Initialize acoustic network components
306        self.channel_manager.initialize()?;
307        self.modem_controller.initialize()?;
308        self.protocol_handler.initialize()?;
309
310        // Register default local transducer node interface if none registered
311        if self.nodes.is_empty() {
312            let local_transducer = AcousticNode {
313                node_id: "acoustic_local_transducer".to_string(),
314                node_type: NodeType::Gateway,
315                capabilities: AcousticCapabilities {
316                    frequency_range: (20000.0, 50000.0),
317                    bandwidth: 5000.0,
318                    max_range: 2000.0,
319                    data_rate: 2400.0,
320                    modulation: ModulationType::OFDM,
321                    error_correction: ErrorCorrectionType::ReedSolomon,
322                },
323                location: None,
324                status: NodeStatus::Active,
325                signal_strength: -30.0,
326                battery_level: 100.0,
327            };
328            self.nodes.insert(local_transducer.node_id.clone(), local_transducer);
329        }
330        Ok(())
331    }
332
333    /// Return the discovered acoustic nodes from the node registry.
334    pub fn discover_nodes(&mut self) -> Result<Vec<AcousticNode>, MeshError> {
335        Ok(self.nodes.values().cloned().collect())
336    }
337
338    /// Enqueue message into the acoustic modem transmission buffer.
339    pub fn send_message(&mut self, message: &StoredMessage) -> Result<(), MeshError> {
340        self.tx_queue.push(message.clone());
341        Ok(())
342    }
343
344    /// Enqueue payload into the acoustic transmission buffer.
345    pub fn send_payload(
346        &mut self,
347        destination: &str,
348        payload: &[u8],
349        priority: MessagePriority,
350    ) -> Result<(), MeshError> {
351        let message = StoredMessage {
352            message_id: format!("acoustic_{}", self.tx_queue.len() + 1),
353            source: "local_node".to_string(),
354            destination: destination.to_string(),
355            payload: payload.to_vec(),
356            priority,
357            timestamp: Instant::now(),
358            ttl: Duration::from_secs(3600),
359            delivery_attempts: 0,
360            status: MessageStatus::Pending,
361        };
362        self.tx_queue.push(message);
363        Ok(())
364    }
365
366    /// Inspect the current acoustic transmission queue.
367    pub fn tx_queue(&self) -> &[StoredMessage] {
368        &self.tx_queue
369    }
370
371    /// Number of nodes in the registry.
372    pub fn get_node_count(&self) -> u32 {
373        self.nodes.len() as u32
374    }
375
376    /// Optimize acoustic discovery across available channels.
377    pub fn optimize_discovery(&mut self) -> Result<(), MeshError> {
378        if self.channel_manager.active_channel_count() == 0 && self.channel_manager.available_channel_count() > 0 {
379            let ch_id = self.channel_manager.available_channels[0].channel_id.clone();
380            self.channel_manager.allocate_channel(&ch_id);
381        }
382        Ok(())
383    }
384}
385
386impl AcousticChannelManager {
387    /// Construct a `AcousticChannelManager` with default field values.
388    pub fn new() -> Self {
389        Self {
390            available_channels: Vec::new(),
391            active_channels: HashMap::new(),
392            channel_allocation: ChannelAllocationStrategy::Adaptive,
393        }
394    }
395
396    /// Initialize `AcousticChannelManager`; `Ok` when ready.
397    pub fn initialize(&mut self) -> Result<(), MeshError> {
398        // Pre-allocate standard acoustic channels (20-50 kHz range).
399        for i in 0..5 {
400            let freq = 20000.0 + i as f64 * 6000.0;
401            self.available_channels.push(AcousticChannel {
402                channel_id: format!("acoustic_ch_{}", i),
403                frequency: freq,
404                bandwidth: 1000.0,
405                power_level: 100.0,
406                modulation: ModulationType::FSK,
407                noise_floor: -80.0,
408                interference_level: 0.0,
409            });
410        }
411        Ok(())
412    }
413
414    /// Allocate `channel_id` if free; `None` when already taken.
415    pub fn allocate_channel(&mut self, channel_id: &str) -> Option<&AcousticChannel> {
416        if let Some(pos) = self
417            .available_channels
418            .iter()
419            .position(|c| c.channel_id == channel_id)
420        {
421            let channel = self.available_channels.remove(pos);
422            self.active_channels
423                .insert(channel.channel_id.clone(), channel);
424        }
425        self.active_channels.get(channel_id)
426    }
427
428    /// Free `channel_id` if allocated.
429    pub fn release_channel(&mut self, channel_id: &str) {
430        if let Some(channel) = self.active_channels.remove(channel_id) {
431            self.available_channels.push(channel);
432        }
433    }
434
435    /// Channels currently unallocated.
436    pub fn available_channel_count(&self) -> usize {
437        self.available_channels.len()
438    }
439
440    /// Channels currently allocated.
441    pub fn active_channel_count(&self) -> usize {
442        self.active_channels.len()
443    }
444
445    /// The channel allocation strategy.
446    pub fn allocation_strategy(&self) -> &ChannelAllocationStrategy {
447        &self.channel_allocation
448    }
449}
450
451impl AcousticModemController {
452    /// Construct a `AcousticModemController` with default field values.
453    pub fn new() -> Self {
454        Self {
455            modem_type: ModemType::SoftwareDefined,
456            transmission_power: 100.0,    // 100W
457            receiver_sensitivity: -120.0, // -120dBm
458            signal_processing: SignalProcessingConfig {
459                sampling_rate: 192000.0, // 192 kHz
460                fft_size: 1024,
461                filter_type: FilterType::BandPass,
462                noise_reduction: true,
463                equalization: true,
464            },
465        }
466    }
467
468    /// Initialize `AcousticModemController`; `Ok` when ready.
469    pub fn initialize(&mut self) -> Result<(), MeshError> {
470        Ok(())
471    }
472
473    /// The modem type.
474    pub fn modem_type(&self) -> &ModemType {
475        &self.modem_type
476    }
477
478    /// Configured transmit power.
479    pub fn transmission_power(&self) -> f64 {
480        self.transmission_power
481    }
482
483    /// Set transmit power.
484    pub fn set_transmission_power(&mut self, power: f64) {
485        self.transmission_power = power.max(0.0);
486    }
487
488    /// Configured receiver sensitivity.
489    pub fn receiver_sensitivity(&self) -> f64 {
490        self.receiver_sensitivity
491    }
492
493    /// The signal-processing configuration.
494    pub fn signal_processing(&self) -> &SignalProcessingConfig {
495        &self.signal_processing
496    }
497
498    /// Estimate maximum communication range based on transmission power,
499    /// receiver sensitivity, and acoustic spreading loss (15 dB/km).
500    pub fn estimated_range_km(&self) -> f64 {
501        let snr_margin = self.transmission_power + self.receiver_sensitivity.abs();
502        snr_margin / 15.0
503    }
504}
505
506impl AcousticProtocolHandler {
507    /// Construct a `AcousticProtocolHandler` with default field values.
508    pub fn new() -> Self {
509        Self {
510            protocol_stack: AcousticProtocolStack::new(),
511            packet_handler: PacketHandler::new(),
512            flow_control: FlowControl::new(),
513            error_handling: ErrorHandling::new(),
514        }
515    }
516
517    /// Initialize `AcousticProtocolHandler`; `Ok` when ready.
518    pub fn initialize(&mut self) -> Result<(), MeshError> {
519        Ok(())
520    }
521
522    /// The acoustic protocol stack.
523    pub fn protocol_stack(&self) -> &AcousticProtocolStack {
524        &self.protocol_stack
525    }
526
527    /// The packet handler.
528    pub fn packet_handler(&self) -> &PacketHandler {
529        &self.packet_handler
530    }
531
532    /// The flow-control config.
533    pub fn flow_control(&self) -> &FlowControl {
534        &self.flow_control
535    }
536
537    /// The error-handling config.
538    pub fn error_handling(&self) -> &ErrorHandling {
539        &self.error_handling
540    }
541}
542
543impl AcousticProtocolStack {
544    /// Construct a `AcousticProtocolStack` with default field values.
545    pub fn new() -> Self {
546        Self {
547            physical_layer: PhysicalLayer::new(),
548            data_link_layer: DataLinkLayer::new(),
549            network_layer: NetworkLayer::new(),
550            transport_layer: TransportLayer::new(),
551        }
552    }
553}
554
555impl PhysicalLayer {
556    /// Construct a `PhysicalLayer` with default field values.
557    pub fn new() -> Self {
558        Self {
559            modulation: ModulationType::FSK,
560            coding: ErrorCorrectionType::ReedSolomon,
561            frequency_hopping: true,
562            power_control: true,
563        }
564    }
565}
566
567impl DataLinkLayer {
568    /// Construct a `DataLinkLayer` with default field values.
569    pub fn new() -> Self {
570        Self {
571            mac_protocol: MacProtocol::CSMA,
572            frame_format: FrameFormat::Adaptive,
573            error_detection: ErrorDetection::CRC,
574            retransmission: RetransmissionStrategy::Adaptive,
575        }
576    }
577}
578
579impl NetworkLayer {
580    /// Construct a `NetworkLayer` with default field values.
581    pub fn new() -> Self {
582        Self {
583            routing_protocol: RoutingProtocol::Geographic,
584            addressing_scheme: AddressingScheme::Geographic,
585            fragmentation: true,
586            congestion_control: true,
587        }
588    }
589}
590
591impl TransportLayer {
592    /// Construct a `TransportLayer` with default field values.
593    pub fn new() -> Self {
594        Self {
595            transport_protocol: TransportProtocol::DTN,
596            reliability: ReliabilityLevel::SemiReliable,
597            flow_control: FlowControlType::CreditBased,
598            congestion_control: CongestionControlType::RED,
599        }
600    }
601}
602
603impl PacketHandler {
604    /// Construct a `PacketHandler` with default field values.
605    pub fn new() -> Self {
606        Self {}
607    }
608}
609
610impl FlowControl {
611    /// Construct a `FlowControl` with default field values.
612    pub fn new() -> Self {
613        Self {}
614    }
615}
616
617impl ErrorHandling {
618    /// Construct a `ErrorHandling` with default field values.
619    pub fn new() -> Self {
620        Self {}
621    }
622}