wifi-densepose-mat 0.3.2

Mass Casualty Assessment Tool - WiFi-based disaster survivor detection
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Domain events for the wifi-Mat system.
#![allow(missing_docs)]

use chrono::{DateTime, Utc};

use super::{
    AlertId, AlertResolution, Coordinates3D, Priority, ScanZoneId, SurvivorId, TriageStatus,
    VitalSignsReading,
};

/// All domain events in the system
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DomainEvent {
    /// Detection-related events
    Detection(DetectionEvent),
    /// Alert-related events
    Alert(AlertEvent),
    /// Zone-related events
    Zone(ZoneEvent),
    /// System-level events
    System(SystemEvent),
    /// Tracking-related events
    Tracking(TrackingEvent),
}

impl DomainEvent {
    /// Get the timestamp of the event
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            DomainEvent::Detection(e) => e.timestamp(),
            DomainEvent::Alert(e) => e.timestamp(),
            DomainEvent::Zone(e) => e.timestamp(),
            DomainEvent::System(e) => e.timestamp(),
            DomainEvent::Tracking(e) => e.timestamp(),
        }
    }

    /// Get event type name
    pub fn event_type(&self) -> &'static str {
        match self {
            DomainEvent::Detection(e) => e.event_type(),
            DomainEvent::Alert(e) => e.event_type(),
            DomainEvent::Zone(e) => e.event_type(),
            DomainEvent::System(e) => e.event_type(),
            DomainEvent::Tracking(e) => e.event_type(),
        }
    }
}

/// Detection-related events
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DetectionEvent {
    /// New survivor detected
    SurvivorDetected {
        survivor_id: SurvivorId,
        zone_id: ScanZoneId,
        vital_signs: VitalSignsReading,
        location: Option<Coordinates3D>,
        timestamp: DateTime<Utc>,
    },

    /// Survivor vital signs updated
    VitalsUpdated {
        survivor_id: SurvivorId,
        previous_triage: TriageStatus,
        current_triage: TriageStatus,
        confidence: f64,
        timestamp: DateTime<Utc>,
    },

    /// Survivor triage status changed
    TriageStatusChanged {
        survivor_id: SurvivorId,
        previous: TriageStatus,
        current: TriageStatus,
        reason: String,
        timestamp: DateTime<Utc>,
    },

    /// Survivor location refined
    LocationRefined {
        survivor_id: SurvivorId,
        previous: Option<Coordinates3D>,
        current: Coordinates3D,
        uncertainty_reduced: bool,
        timestamp: DateTime<Utc>,
    },

    /// Survivor no longer detected
    SurvivorLost {
        survivor_id: SurvivorId,
        last_detection: DateTime<Utc>,
        reason: LostReason,
        timestamp: DateTime<Utc>,
    },

    /// Survivor rescued
    SurvivorRescued {
        survivor_id: SurvivorId,
        rescue_team: Option<String>,
        timestamp: DateTime<Utc>,
    },

    /// Survivor marked deceased
    SurvivorDeceased {
        survivor_id: SurvivorId,
        timestamp: DateTime<Utc>,
    },
}

impl DetectionEvent {
    /// Get the timestamp
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            Self::SurvivorDetected { timestamp, .. } => *timestamp,
            Self::VitalsUpdated { timestamp, .. } => *timestamp,
            Self::TriageStatusChanged { timestamp, .. } => *timestamp,
            Self::LocationRefined { timestamp, .. } => *timestamp,
            Self::SurvivorLost { timestamp, .. } => *timestamp,
            Self::SurvivorRescued { timestamp, .. } => *timestamp,
            Self::SurvivorDeceased { timestamp, .. } => *timestamp,
        }
    }

    /// Get the event type name
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::SurvivorDetected { .. } => "SurvivorDetected",
            Self::VitalsUpdated { .. } => "VitalsUpdated",
            Self::TriageStatusChanged { .. } => "TriageStatusChanged",
            Self::LocationRefined { .. } => "LocationRefined",
            Self::SurvivorLost { .. } => "SurvivorLost",
            Self::SurvivorRescued { .. } => "SurvivorRescued",
            Self::SurvivorDeceased { .. } => "SurvivorDeceased",
        }
    }

    /// Get the survivor ID associated with this event
    pub fn survivor_id(&self) -> &SurvivorId {
        match self {
            Self::SurvivorDetected { survivor_id, .. } => survivor_id,
            Self::VitalsUpdated { survivor_id, .. } => survivor_id,
            Self::TriageStatusChanged { survivor_id, .. } => survivor_id,
            Self::LocationRefined { survivor_id, .. } => survivor_id,
            Self::SurvivorLost { survivor_id, .. } => survivor_id,
            Self::SurvivorRescued { survivor_id, .. } => survivor_id,
            Self::SurvivorDeceased { survivor_id, .. } => survivor_id,
        }
    }
}

/// Reasons for losing a survivor signal
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LostReason {
    /// Survivor was rescued (signal expected to stop)
    Rescued,
    /// Detection determined to be false positive
    FalsePositive,
    /// Signal lost (interference, debris shift, etc.)
    SignalLost,
    /// Zone was deactivated
    ZoneDeactivated,
    /// Sensor malfunction
    SensorFailure,
    /// Unknown reason
    Unknown,
}

/// Alert-related events
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlertEvent {
    /// New alert generated
    AlertGenerated {
        alert_id: AlertId,
        survivor_id: SurvivorId,
        priority: Priority,
        timestamp: DateTime<Utc>,
    },

    /// Alert acknowledged by rescue team
    AlertAcknowledged {
        alert_id: AlertId,
        acknowledged_by: String,
        timestamp: DateTime<Utc>,
    },

    /// Alert escalated
    AlertEscalated {
        alert_id: AlertId,
        previous_priority: Priority,
        new_priority: Priority,
        reason: String,
        timestamp: DateTime<Utc>,
    },

    /// Alert resolved
    AlertResolved {
        alert_id: AlertId,
        resolution: AlertResolution,
        timestamp: DateTime<Utc>,
    },

    /// Alert cancelled
    AlertCancelled {
        alert_id: AlertId,
        reason: String,
        timestamp: DateTime<Utc>,
    },
}

impl AlertEvent {
    /// Get the timestamp
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            Self::AlertGenerated { timestamp, .. } => *timestamp,
            Self::AlertAcknowledged { timestamp, .. } => *timestamp,
            Self::AlertEscalated { timestamp, .. } => *timestamp,
            Self::AlertResolved { timestamp, .. } => *timestamp,
            Self::AlertCancelled { timestamp, .. } => *timestamp,
        }
    }

    /// Get the event type name
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::AlertGenerated { .. } => "AlertGenerated",
            Self::AlertAcknowledged { .. } => "AlertAcknowledged",
            Self::AlertEscalated { .. } => "AlertEscalated",
            Self::AlertResolved { .. } => "AlertResolved",
            Self::AlertCancelled { .. } => "AlertCancelled",
        }
    }

    /// Get the alert ID associated with this event
    pub fn alert_id(&self) -> &AlertId {
        match self {
            Self::AlertGenerated { alert_id, .. } => alert_id,
            Self::AlertAcknowledged { alert_id, .. } => alert_id,
            Self::AlertEscalated { alert_id, .. } => alert_id,
            Self::AlertResolved { alert_id, .. } => alert_id,
            Self::AlertCancelled { alert_id, .. } => alert_id,
        }
    }
}

/// Zone-related events
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ZoneEvent {
    /// Zone activated
    ZoneActivated {
        zone_id: ScanZoneId,
        zone_name: String,
        timestamp: DateTime<Utc>,
    },

    /// Zone scan completed
    ZoneScanCompleted {
        zone_id: ScanZoneId,
        detections_found: u32,
        scan_duration_ms: u64,
        timestamp: DateTime<Utc>,
    },

    /// Zone paused
    ZonePaused {
        zone_id: ScanZoneId,
        reason: String,
        timestamp: DateTime<Utc>,
    },

    /// Zone resumed
    ZoneResumed {
        zone_id: ScanZoneId,
        timestamp: DateTime<Utc>,
    },

    /// Zone marked complete
    ZoneCompleted {
        zone_id: ScanZoneId,
        total_survivors_found: u32,
        timestamp: DateTime<Utc>,
    },

    /// Zone deactivated
    ZoneDeactivated {
        zone_id: ScanZoneId,
        reason: String,
        timestamp: DateTime<Utc>,
    },
}

impl ZoneEvent {
    /// Get the timestamp
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            Self::ZoneActivated { timestamp, .. } => *timestamp,
            Self::ZoneScanCompleted { timestamp, .. } => *timestamp,
            Self::ZonePaused { timestamp, .. } => *timestamp,
            Self::ZoneResumed { timestamp, .. } => *timestamp,
            Self::ZoneCompleted { timestamp, .. } => *timestamp,
            Self::ZoneDeactivated { timestamp, .. } => *timestamp,
        }
    }

    /// Get the event type name
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::ZoneActivated { .. } => "ZoneActivated",
            Self::ZoneScanCompleted { .. } => "ZoneScanCompleted",
            Self::ZonePaused { .. } => "ZonePaused",
            Self::ZoneResumed { .. } => "ZoneResumed",
            Self::ZoneCompleted { .. } => "ZoneCompleted",
            Self::ZoneDeactivated { .. } => "ZoneDeactivated",
        }
    }

    /// Get the zone ID associated with this event
    pub fn zone_id(&self) -> &ScanZoneId {
        match self {
            Self::ZoneActivated { zone_id, .. } => zone_id,
            Self::ZoneScanCompleted { zone_id, .. } => zone_id,
            Self::ZonePaused { zone_id, .. } => zone_id,
            Self::ZoneResumed { zone_id, .. } => zone_id,
            Self::ZoneCompleted { zone_id, .. } => zone_id,
            Self::ZoneDeactivated { zone_id, .. } => zone_id,
        }
    }
}

/// System-level events
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SystemEvent {
    /// System started
    SystemStarted {
        version: String,
        timestamp: DateTime<Utc>,
    },

    /// System stopped
    SystemStopped {
        reason: String,
        timestamp: DateTime<Utc>,
    },

    /// Sensor connected
    SensorConnected {
        sensor_id: String,
        zone_id: ScanZoneId,
        timestamp: DateTime<Utc>,
    },

    /// Sensor disconnected
    SensorDisconnected {
        sensor_id: String,
        reason: String,
        timestamp: DateTime<Utc>,
    },

    /// Configuration changed
    ConfigChanged {
        setting: String,
        previous_value: String,
        new_value: String,
        timestamp: DateTime<Utc>,
    },

    /// Error occurred
    ErrorOccurred {
        error_type: String,
        message: String,
        severity: ErrorSeverity,
        timestamp: DateTime<Utc>,
    },
}

impl SystemEvent {
    /// Get the timestamp
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            Self::SystemStarted { timestamp, .. } => *timestamp,
            Self::SystemStopped { timestamp, .. } => *timestamp,
            Self::SensorConnected { timestamp, .. } => *timestamp,
            Self::SensorDisconnected { timestamp, .. } => *timestamp,
            Self::ConfigChanged { timestamp, .. } => *timestamp,
            Self::ErrorOccurred { timestamp, .. } => *timestamp,
        }
    }

    /// Get the event type name
    pub fn event_type(&self) -> &'static str {
        match self {
            Self::SystemStarted { .. } => "SystemStarted",
            Self::SystemStopped { .. } => "SystemStopped",
            Self::SensorConnected { .. } => "SensorConnected",
            Self::SensorDisconnected { .. } => "SensorDisconnected",
            Self::ConfigChanged { .. } => "ConfigChanged",
            Self::ErrorOccurred { .. } => "ErrorOccurred",
        }
    }
}

/// Error severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ErrorSeverity {
    /// Warning - operation continues
    Warning,
    /// Error - operation may be affected
    Error,
    /// Critical - immediate attention required
    Critical,
}

/// Tracking-related domain events.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TrackingEvent {
    /// A tentative track has been confirmed (Tentative → Active).
    TrackBorn {
        track_id: String, // TrackId as string (avoids circular dep)
        survivor_id: SurvivorId,
        zone_id: ScanZoneId,
        timestamp: DateTime<Utc>,
    },
    /// An active track lost its signal (Active → Lost).
    TrackLost {
        track_id: String,
        survivor_id: SurvivorId,
        last_position: Option<Coordinates3D>,
        timestamp: DateTime<Utc>,
    },
    /// A lost track was re-linked via fingerprint (Lost → Active).
    TrackReidentified {
        track_id: String,
        survivor_id: SurvivorId,
        gap_secs: f64,
        fingerprint_distance: f32,
        timestamp: DateTime<Utc>,
    },
    /// A lost track expired without re-identification (Lost → Terminated).
    TrackTerminated {
        track_id: String,
        survivor_id: SurvivorId,
        lost_duration_secs: f64,
        timestamp: DateTime<Utc>,
    },
    /// Operator confirmed a survivor as rescued.
    TrackRescued {
        track_id: String,
        survivor_id: SurvivorId,
        timestamp: DateTime<Utc>,
    },
}

impl TrackingEvent {
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            TrackingEvent::TrackBorn { timestamp, .. } => *timestamp,
            TrackingEvent::TrackLost { timestamp, .. } => *timestamp,
            TrackingEvent::TrackReidentified { timestamp, .. } => *timestamp,
            TrackingEvent::TrackTerminated { timestamp, .. } => *timestamp,
            TrackingEvent::TrackRescued { timestamp, .. } => *timestamp,
        }
    }

    pub fn event_type(&self) -> &'static str {
        match self {
            TrackingEvent::TrackBorn { .. } => "TrackBorn",
            TrackingEvent::TrackLost { .. } => "TrackLost",
            TrackingEvent::TrackReidentified { .. } => "TrackReidentified",
            TrackingEvent::TrackTerminated { .. } => "TrackTerminated",
            TrackingEvent::TrackRescued { .. } => "TrackRescued",
        }
    }
}

/// Event store for persisting domain events
pub trait EventStore: Send + Sync {
    /// Append an event to the store
    fn append(&self, event: DomainEvent) -> Result<(), crate::MatError>;

    /// Get all events
    fn all(&self) -> Result<Vec<DomainEvent>, crate::MatError>;

    /// Get events since a timestamp
    fn since(&self, timestamp: DateTime<Utc>) -> Result<Vec<DomainEvent>, crate::MatError>;

    /// Get events for a specific survivor
    fn for_survivor(&self, survivor_id: &SurvivorId) -> Result<Vec<DomainEvent>, crate::MatError>;
}

/// In-memory event store implementation
#[derive(Debug, Default)]
pub struct InMemoryEventStore {
    events: parking_lot::RwLock<Vec<DomainEvent>>,
}

impl InMemoryEventStore {
    /// Create a new in-memory event store
    pub fn new() -> Self {
        Self::default()
    }
}

impl EventStore for InMemoryEventStore {
    fn append(&self, event: DomainEvent) -> Result<(), crate::MatError> {
        self.events.write().push(event);
        Ok(())
    }

    fn all(&self) -> Result<Vec<DomainEvent>, crate::MatError> {
        Ok(self.events.read().clone())
    }

    fn since(&self, timestamp: DateTime<Utc>) -> Result<Vec<DomainEvent>, crate::MatError> {
        Ok(self
            .events
            .read()
            .iter()
            .filter(|e| e.timestamp() >= timestamp)
            .cloned()
            .collect())
    }

    fn for_survivor(&self, survivor_id: &SurvivorId) -> Result<Vec<DomainEvent>, crate::MatError> {
        Ok(self
            .events
            .read()
            .iter()
            .filter(|e| {
                if let DomainEvent::Detection(de) = e {
                    de.survivor_id() == survivor_id
                } else {
                    false
                }
            })
            .cloned()
            .collect())
    }
}

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

    #[test]
    fn test_in_memory_event_store() {
        let store = InMemoryEventStore::new();

        let event = DomainEvent::System(SystemEvent::SystemStarted {
            version: "1.0.0".to_string(),
            timestamp: Utc::now(),
        });

        store.append(event).unwrap();
        let events = store.all().unwrap();
        assert_eq!(events.len(), 1);
    }
}