takproto 0.4.2

Rust library for TAK (Team Awareness Kit) Protocol - send CoT messages to TAK servers with mTLS support
Documentation
# takproto

A Rust library for sending TAK (Team Awareness Kit) Protocol messages to TAK servers.

This library implements TAK Protocol Version 1, which uses Google Protocol Buffers for message encoding with a custom framing format for streaming connections.

## Features

- ✅ TAK Protocol Version 1 implementation
- ✅ Protocol Buffer message encoding/decoding
- ✅ Streaming connection framing (magic byte + varint length)
- ✅ Async/await support with Tokio
- ✅ Send and receive CoT (Cursor on Target) events
- ✅ Type-safe message construction

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
takproto = "0.1"
tokio = { version = "1.40", features = ["full"] }
```

## Quick Start

### Sending a Position Report

```rust
use std::time::{SystemTime, UNIX_EPOCH};
use takproto::{TakClient, proto::CotEvent};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to TAK server
    let mut client = TakClient::connect("127.0.0.1:8087").await?;

    // Get current time
    let now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)?
        .as_millis() as u64;

    // Create a position report
    let event = CotEvent {
        r#type: "a-f-G-U-C".to_string(),     // Friendly ground unit
        uid: "RUST-TAK-1".to_string(),        // Unique identifier
        send_time: now_ms,
        start_time: now_ms,
        stale_time: now_ms + 60_000,          // Valid for 60 seconds
        how: "m-g".to_string(),               // Machine generated
        lat: 37.7749,                         // Latitude
        lon: -122.4194,                       // Longitude
        hae: 10.0,                            // Height above ellipsoid
        ce: 9.9,                              // Circular error
        le: 9.9,                              // Linear error
        ..Default::default()
    };

    // Send the event
    client.send_cot_event(event).await?;

    // Close connection
    client.close().await?;

    Ok(())
}
```

### Receiving Messages

```rust
use takproto::TakClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = TakClient::connect("127.0.0.1:8087").await?;

    loop {
        match client.receive_tak_message().await? {
            Some(message) => {
                if let Some(event) = message.cot_event {
                    println!("Received: {} at {}, {}",
                        event.uid, event.lat, event.lon);
                }
            }
            None => break, // Connection closed
        }
    }

    Ok(())
}
```

## Examples

Run the included examples:

```bash
# Send a position report
cargo run --example send_position

# Send to a specific server
cargo run --example send_position 192.168.1.100:8087

# Listen for messages
cargo run --example listen
```

## CoT Event Types

Common CoT event types:

- `a-f-G-U-C` - Friendly ground unit (combat)
- `a-f-G-U-C-I` - Friendly ground unit (combat infantry)
- `a-f-A` - Friendly aircraft
- `a-h-G` - Hostile ground unit
- `b-m-p-s-m` - Map point (marker)

The type hierarchy follows the CoT type tree specification.

## Protocol Details

### Streaming Message Format

Each message sent over a TAK streaming connection follows this format:

```
<magic byte 0xbf> <message length varint> <protobuf payload>
```

- **Magic byte**: Always `0xbf`
- **Message length**: Unsigned varint encoding the payload length in bytes
- **Payload**: Protocol Buffer encoded `TakMessage`

### TakMessage Structure

```protobuf
message TakMessage {
    optional TakControl takControl = 1;  // Protocol control info
    optional CotEvent cotEvent = 2;       // CoT event data
}
```

### CotEvent Fields

Key fields in a `CotEvent`:

- `type`: CoT event type (e.g., "a-f-G-U-C")
- `uid`: Unique identifier for the entity
- `sendTime`: Message send time (milliseconds since Unix epoch)
- `startTime`: Event start time
- `staleTime`: When the event becomes stale
- `how`: How the event was generated (e.g., "m-g" for machine-generated)
- `lat`, `lon`, `hae`: Position coordinates
- `ce`, `le`: Circular and linear error estimates
- `detail`: Optional detailed information

## Production Considerations

This library currently provides basic TAK Protocol functionality. For production use, you should consider:

1. **TLS/SSL Support**: TAK servers typically require encrypted connections
2. **Authentication**: Implement certificate-based or username/password authentication
3. **Protocol Negotiation**: Handle the XML-based protocol version negotiation handshake
4. **Reconnection Logic**: Automatic reconnection on connection failures
5. **Message Validation**: Validate CoT messages before sending
6. **Error Handling**: Robust error handling and logging

## Protocol Resources

This implementation is based on the TAK Protocol specification included in this repository. See the proto files and README sections for detailed protocol information.

Key concepts:

- **Protocol Version 0**: Legacy XML-based CoT messages
- **Protocol Version 1**: Protocol Buffer-based messages (this implementation)
- **Streaming Connections**: TCP connections to TAK servers
- **Mesh Networks**: UDP broadcast for peer-to-peer discovery

## Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

## License

MIT OR Apache-2.0

---

## Original TAK Protocol Documentation

Below is the original TAK Protocol documentation for reference:

---

*** Traditional Protocol - "Protocol Version 0"

Clients send and receive XML CoT <event> messages.
"Mesh" network participants announce via "SA" messages via UDP datagrams
over multicast to a well known address and port.  Each UDP datagram contains
one (and only one) CoT XML message as its payload.

Messages directed only to specific network participants are send by making
TCP connection to the remote recipient, sending the CoT XML, then closing
the connection.

Streaming connections (to TAK servers) send the same XML-based CoT payloads
over TCP sockets.  The TCP stream is comprised of one CoT <event> after
another.  Messages are delimited and broken apart by searching for the token
"</event>" and breaking apart immediately after that token.
When sending, messages must be prefaced by XML header (<?xml ... ?>),
followed by a newline, followed by the complete XML <event>.  TAK servers
require that no arbitrary newlines follow the </event> end of message and
that the next character immediate commences the next <?xml ... ?> header.

*** TAK Protocol - Design Goals

The goal of the new TAK Protocol design is to allow interoperation with
other legacy clients and TAK server, as well as to strongly identify
what rendition of communication will be used in a session.  This is to allow
for future expansion or complete revision of the protocol while allowing
an opportunity to support mixed client versions (and varying versions of TAK
servers).

[... rest of protocol documentation truncated for brevity ...]