peat-ffi 0.2.8

FFI bindings for Peat protocol (Kotlin/Swift via UniFFI)
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
//! Peat CoT Test Client
//!
//! This example creates a Peat node that publishes mock data for testing
//! mDNS peer discovery with consumer plugins.
//!
//! # Running the Example
//!
//! ```bash
//! CXXFLAGS="-include cstdint" cargo run --example peat_cot_client -p peat-ffi --features sync
//! ```
//!
//! # What It Does
//!
//! 1. Creates a Peat node with mDNS discovery enabled
//! 2. Publishes moving tracks that fly patterns over Atlanta
//! 3. Starts P2P sync and waits for peers to discover via mDNS
//!
//! # IMPORTANT: Test Isolation
//!
//! By default, this uses a TEST-ONLY formation ID (`peat-test-cot-client`) that is
//! isolated from production deployments. To test with a consumer plugin, you must
//! explicitly set the same formation ID:
//!
//! ```bash
//! PEAT_APP_ID=default-formation cargo run --example peat_cot_client ...
//! ```
//!
//! This prevents test data from accidentally polluting production deployments.

use peat_ffi::{create_node, NodeConfig};
use std::f64::consts::PI;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

/// Atlanta area center coordinates
const ATLANTA_LAT: f64 = 33.749;
const ATLANTA_LON: f64 = -84.388;

/// Flight pattern configuration
struct FlightPattern {
    name: &'static str,
    pattern_type: PatternType,
    center_lat: f64,
    center_lon: f64,
    radius_deg: f64,   // Pattern radius in degrees
    altitude_m: f64,   // Altitude in meters
    speed_factor: f64, // How fast the pattern progresses
    classification: &'static str,
    category: &'static str,
}

#[derive(Clone, Copy, Debug)]
enum PatternType {
    Orbit,     // Circular orbit
    Racetrack, // Oval racetrack pattern
    Figure8,   // Figure-8 pattern
    Lawnmower, // Search pattern (back and forth)
}

fn main() {
    println!("=== Peat CoT Test Client - Atlanta Flight Patterns ===\n");

    // Use TEST-ONLY formation by default to avoid polluting production deployments
    // Set PEAT_APP_ID=default-formation to test with a real consumer plugin
    let app_id = std::env::var("PEAT_APP_ID").unwrap_or_else(|_| "peat-test-cot-client".into());
    let shared_key = std::env::var("PEAT_SHARED_KEY")
        .unwrap_or_else(|_| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into());

    // Create storage directory
    let storage_path =
        std::env::var("PEAT_STORAGE_PATH").unwrap_or_else(|_| "/tmp/peat-tak-client".into());
    std::fs::create_dir_all(&storage_path).expect("Failed to create storage directory");

    println!("Configuration:");
    println!("  Formation: {}", app_id);
    println!("  Storage: {}", storage_path);
    println!("  Area: Atlanta ({:.3}, {:.3})", ATLANTA_LAT, ATLANTA_LON);
    println!();

    println!("Creating Peat node with mDNS discovery...");
    let config = NodeConfig {
        app_id: app_id.clone(),
        shared_key: shared_key.clone(),
        bind_address: Some("0.0.0.0:42008".into()), // Fixed port for testing
        storage_path: storage_path.clone(),
        transport: None, // Use default Iroh transport only
    };

    let node: Arc<peat_ffi::PeatNode> = match create_node(config) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("Failed to create Peat node: {:?}", e);
            return;
        }
    };

    println!("Node ID: {}", node.node_id());
    println!("Endpoint: {}", node.endpoint_addr());
    println!();

    // Define flight patterns over Atlanta
    let patterns = vec![
        FlightPattern {
            name: "HAWK-1",
            pattern_type: PatternType::Orbit,
            center_lat: ATLANTA_LAT + 0.02, // North of downtown
            center_lon: ATLANTA_LON - 0.01,
            radius_deg: 0.015,
            altitude_m: 300.0,
            speed_factor: 1.0,
            classification: "a-f-A-M-F-Q", // Friendly UAV
            category: "aircraft",
        },
        FlightPattern {
            name: "HAWK-2",
            pattern_type: PatternType::Racetrack,
            center_lat: ATLANTA_LAT - 0.015, // South of downtown
            center_lon: ATLANTA_LON + 0.02,
            radius_deg: 0.02,
            altitude_m: 250.0,
            speed_factor: 0.8,
            classification: "a-f-A-M-F-Q",
            category: "aircraft",
        },
        FlightPattern {
            name: "SCOUT-1",
            pattern_type: PatternType::Figure8,
            center_lat: ATLANTA_LAT, // Over downtown
            center_lon: ATLANTA_LON,
            radius_deg: 0.025,
            altitude_m: 400.0,
            speed_factor: 0.6,
            classification: "a-f-A-M-F-Q",
            category: "aircraft",
        },
        FlightPattern {
            name: "SEARCH-1",
            pattern_type: PatternType::Lawnmower,
            center_lat: ATLANTA_LAT + 0.01, // East of downtown (near airport)
            center_lon: ATLANTA_LON + 0.04,
            radius_deg: 0.03,
            altitude_m: 200.0,
            speed_factor: 0.5,
            classification: "a-f-A-M-F-Q",
            category: "aircraft",
        },
    ];

    // Initial publish
    let mut time_offset = 0u64;
    publish_flight_patterns(&node, &patterns, time_offset);
    publish_cells_and_nodes(&node);

    // Verify data was stored
    println!("\n--- Verifying stored data ---");
    match node.list_documents("cells") {
        Ok(docs) => println!("Cells: {} stored", docs.len()),
        Err(e) => println!("Error listing cells: {:?}", e),
    }
    match node.list_documents("tracks") {
        Ok(docs) => println!("Tracks: {} stored", docs.len()),
        Err(e) => println!("Error listing tracks: {:?}", e),
    }
    match node.list_documents("nodes") {
        Ok(docs) => println!("Nodes: {} stored", docs.len()),
        Err(e) => println!("Error listing nodes: {:?}", e),
    }

    // Start sync
    println!("\n--- Starting P2P sync with mDNS discovery ---");
    if let Err(e) = node.start_sync() {
        eprintln!("Failed to start sync: {:?}", e);
        return;
    }
    println!("Sync started. Initial peer count: {}", node.peer_count());

    // Keep running and update positions
    println!("\nFlying patterns over Atlanta... (Ctrl+C to exit)");
    println!("Consumer plugins should discover this node via mDNS.\n");

    let mut last_node_count = 0;
    loop {
        std::thread::sleep(std::time::Duration::from_secs(2));
        time_offset += 2;

        let peers = node.peer_count();
        let connected = node.connected_peers();

        // Update track positions and node positions/heartbeats
        publish_flight_patterns(&node, &patterns, time_offset);
        update_node_positions(&node, &patterns, time_offset);

        // Check for received nodes (consumer PLI)
        let nodes = node.get_nodes().unwrap_or_default();

        // Log new nodes received from consumers
        if nodes.len() != last_node_count {
            println!("\n=== Received {} nodes from network ===", nodes.len());
            for p in &nodes {
                // Skip our own nodes (they have "node-" prefix)
                if p.id.starts_with("node-") {
                    continue;
                }
                println!(
                    "  [PLI] {} ({}) @ {:.4}, {:.4} - {}",
                    p.name,
                    p.id,
                    p.lat,
                    p.lon,
                    p.status.as_str()
                );
            }
            println!();
            last_node_count = nodes.len();
        }

        println!("[t={}s] Peers: {} | Tracks updated", time_offset, peers);

        if !connected.is_empty() {
            println!("  Connected: {:?}", connected);
        }
    }
}

fn current_timestamp() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64
}

/// Calculate position for a given flight pattern at a given time
fn calculate_position(pattern: &FlightPattern, time_secs: u64) -> (f64, f64, f64) {
    let t = (time_secs as f64) * pattern.speed_factor * 0.1; // Scale time for smooth movement

    let (lat_offset, lon_offset) = match pattern.pattern_type {
        PatternType::Orbit => {
            // Simple circular orbit
            let angle = t % (2.0 * PI);
            (
                pattern.radius_deg * angle.sin(),
                pattern.radius_deg * angle.cos(),
            )
        }
        PatternType::Racetrack => {
            // Oval racetrack: two semicircles connected by straight segments
            let cycle = t % (2.0 * PI);
            if cycle < PI / 2.0 {
                // First straight
                let progress = cycle / (PI / 2.0);
                (
                    pattern.radius_deg * 0.5,
                    pattern.radius_deg * (progress - 0.5),
                )
            } else if cycle < PI {
                // First turn
                let angle = (cycle - PI / 2.0) * 2.0;
                (
                    pattern.radius_deg * 0.5 * angle.cos(),
                    pattern.radius_deg * 0.5 + pattern.radius_deg * 0.5 * angle.sin(),
                )
            } else if cycle < 3.0 * PI / 2.0 {
                // Second straight
                let progress = (cycle - PI) / (PI / 2.0);
                (
                    -pattern.radius_deg * 0.5,
                    pattern.radius_deg * (0.5 - progress),
                )
            } else {
                // Second turn
                let angle = (cycle - 3.0 * PI / 2.0) * 2.0 + PI;
                (
                    pattern.radius_deg * 0.5 * angle.cos(),
                    -pattern.radius_deg * 0.5 + pattern.radius_deg * 0.5 * angle.sin(),
                )
            }
        }
        PatternType::Figure8 => {
            // Figure-8 using lemniscate of Bernoulli
            let angle = t % (2.0 * PI);
            let denom = 1.0 + angle.sin().powi(2);
            (
                pattern.radius_deg * angle.sin() / denom,
                pattern.radius_deg * angle.sin() * angle.cos() / denom,
            )
        }
        PatternType::Lawnmower => {
            // Back and forth search pattern
            let row_time = 10.0; // seconds per row
            let total_rows = 6.0;
            let cycle_time = row_time * total_rows;
            let t_cycle = t % cycle_time;
            let row = (t_cycle / row_time).floor();
            let row_progress = (t_cycle % row_time) / row_time;

            let lat_offset = pattern.radius_deg * (row / total_rows - 0.5);
            let lon_offset = if row as i32 % 2 == 0 {
                pattern.radius_deg * (row_progress - 0.5)
            } else {
                pattern.radius_deg * (0.5 - row_progress)
            };
            (lat_offset, lon_offset)
        }
    };

    let lat = pattern.center_lat + lat_offset;
    let lon = pattern.center_lon + lon_offset;
    let alt = pattern.altitude_m;

    (lat, lon, alt)
}

/// Calculate heading based on movement direction
fn calculate_heading(pattern: &FlightPattern, time_secs: u64) -> f64 {
    let (lat1, lon1, _) = calculate_position(pattern, time_secs);
    let (lat2, lon2, _) = calculate_position(pattern, time_secs + 1);

    let dlat = lat2 - lat1;
    let dlon = lon2 - lon1;

    let heading_rad = dlon.atan2(dlat);
    let heading_deg = heading_rad.to_degrees();

    // Normalize to 0-360
    if heading_deg < 0.0 {
        heading_deg + 360.0
    } else {
        heading_deg
    }
}

/// Publish flight pattern tracks
fn publish_flight_patterns(node: &peat_ffi::PeatNode, patterns: &[FlightPattern], time_secs: u64) {
    let now = current_timestamp();

    for (i, pattern) in patterns.iter().enumerate() {
        let (lat, lon, alt) = calculate_position(pattern, time_secs);
        let heading = calculate_heading(pattern, time_secs);

        let track_id = format!("track-{}", pattern.name.to_lowercase().replace('-', "_"));

        let track = serde_json::json!({
            "id": track_id,
            "source_node": format!("node-{}", pattern.name.to_lowercase()),
            "cell_id": "cell-atlanta-001",
            "formation_id": "atlanta-isr",
            "lat": lat,
            "lon": lon,
            "hae": alt,
            "heading": heading,
            "speed": 25.0 + (i as f64 * 5.0),  // Varying speeds
            "classification": pattern.classification,
            "confidence": 0.95,
            "category": pattern.category,
            "attributes": {
                "callsign": pattern.name,
                "pattern": format!("{:?}", pattern.pattern_type),
                "altitude_ft": (alt * 3.28084) as i32
            },
            "created_at": now,
            "last_update": now
        });

        let json = track.to_string();
        if let Err(e) = node.put_document("tracks", &track_id, &json) {
            eprintln!("Error publishing track {}: {:?}", track_id, e);
        } else {
            // Sync the document to connected peers
            if let Err(e) = node.sync_document("tracks", &track_id) {
                // Only log at debug level - sync may fail if no peers connected yet
                if node.peer_count() > 0 {
                    eprintln!("Error syncing track {}: {:?}", track_id, e);
                }
            }
        }
    }
}

/// Publish cells and nodes (static data)
fn publish_cells_and_nodes(node: &peat_ffi::PeatNode) {
    println!("--- Publishing cells and nodes ---");

    // Publish Atlanta cell
    let cell = serde_json::json!({
        "id": "cell-atlanta-001",
        "name": "Atlanta ISR Cell",
        "status": "active",
        "node_count": 4,
        "center_lat": ATLANTA_LAT,
        "center_lon": ATLANTA_LON,
        "capabilities": ["ISR", "SURVEILLANCE", "RECON"],
        "formation_id": "atlanta-isr",
        "leader_id": "node-hawk_1",
        "last_update": current_timestamp()
    });

    let json = cell.to_string();
    match node.put_document("cells", "cell-atlanta-001", &json) {
        Ok(()) => println!("  Published cell: cell-atlanta-001"),
        Err(e) => eprintln!("  Error publishing cell: {:?}", e),
    }

    // Publish nodes
    let nodes = vec![
        (
            "HAWK-1",
            "UAV",
            ATLANTA_LAT + 0.02,
            ATLANTA_LON - 0.01,
            300.0,
        ),
        (
            "HAWK-2",
            "UAV",
            ATLANTA_LAT - 0.015,
            ATLANTA_LON + 0.02,
            250.0,
        ),
        ("SCOUT-1", "UAV", ATLANTA_LAT, ATLANTA_LON, 400.0),
        (
            "SEARCH-1",
            "UAV",
            ATLANTA_LAT + 0.01,
            ATLANTA_LON + 0.04,
            200.0,
        ),
    ];

    for (name, ptype, lat, lon, alt) in nodes {
        let node_id = format!("node-{}", name.to_lowercase().replace('-', "_"));
        let node_doc = serde_json::json!({
            "id": node_id,
            "name": name,
            "node_type": ptype,
            "lat": lat,
            "lon": lon,
            "hae": alt,
            "readiness": 0.95,
            "cell_id": "cell-atlanta-001",
            "capabilities": ["ISR", "EO/IR"],
            "status": "active",
            "last_heartbeat": current_timestamp()
        });

        let json = node_doc.to_string();
        match node.put_document("nodes", &node_id, &json) {
            Ok(()) => println!("  Published node: {}", node_id),
            Err(e) => eprintln!("  Error publishing node {}: {:?}", node_id, e),
        }
    }
}

/// Update node positions and heartbeats (called every refresh cycle)
fn update_node_positions(node: &peat_ffi::PeatNode, patterns: &[FlightPattern], time_secs: u64) {
    let now = current_timestamp();

    for pattern in patterns {
        let (lat, lon, alt) = calculate_position(pattern, time_secs);
        let heading = calculate_heading(pattern, time_secs);

        let node_id = format!("node-{}", pattern.name.to_lowercase().replace('-', "_"));

        let node_doc = serde_json::json!({
            "id": node_id,
            "name": pattern.name,
            "node_type": "UAV",
            "lat": lat,
            "lon": lon,
            "hae": alt,
            "heading": heading,
            "speed": 25.0,
            "readiness": 0.95,
            "cell_id": "cell-atlanta-001",
            "capabilities": ["ISR", "EO/IR"],
            "status": "active",
            "last_heartbeat": now
        });

        let json = node_doc.to_string();
        if let Err(e) = node.put_document("nodes", &node_id, &json) {
            eprintln!("Error updating node {}: {:?}", node_id, e);
        }
    }
}