takproto 0.4.2

Rust library for TAK (Team Awareness Kit) Protocol - send CoT messages to TAK servers with mTLS support
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
/// Helper functions for creating common CoT detail elements
use crate::proto::{Contact, Track, Group, Status, Takv, PrecisionLocation};

/// Create a URL element for iTAK/ATAK links
///
/// The `<url>` element is used by iTAK to display clickable links in the details panel.
/// This is often more compatible than `<link>` elements across different TAK client versions.
///
/// # Arguments
///
/// * `url` - The URL to open (must start with http:// or https://)
/// * `name` - Display name for the link (shown to the user)
///
/// # Example
///
/// ```
/// use takproto::helpers::url_element;
///
/// let xml = url_element("https://www.example.com", "View Website");
/// // Returns: <url url="https://www.example.com" name="View Website"/>
/// ```
pub fn url_element(url: &str, name: &str) -> String {
    format!(r#"<url url="{}" name="{}"/>"#, url, name)
}

/// Create multiple URL elements
///
/// # Example
///
/// ```
/// use takproto::helpers::url_elements;
///
/// let urls = vec![
///     ("https://example.com/report", "View Report"),
///     ("https://example.com/photo.jpg", "View Photo"),
/// ];
/// let xml = url_elements(&urls);
/// ```
pub fn url_elements(urls: &[(&str, &str)]) -> String {
    urls.iter()
        .map(|(url, name)| url_element(url, name))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Create a link element for TAK protocol compatibility
///
/// The `<link>` element is the official TAK protocol link format.
/// However, some TAK clients (especially older iTAK versions) prefer `<url>` elements.
///
/// # Arguments
///
/// * `uid` - Must match the parent CoT event's UID
/// * `cot_type` - Must match the parent CoT event's type
/// * `url` - The URL to open
/// * `remarks` - Display text for the link
///
/// # Example
///
/// ```
/// use takproto::helpers::link_element;
///
/// let xml = link_element("MARKER-001", "b-m-p-s-m", "https://example.com", "Click Here");
/// ```
pub fn link_element(uid: &str, cot_type: &str, url: &str, remarks: &str) -> String {
    format!(
        r#"<link uid="{}" type="{}" relation="p-p" url="{}" mime="text/html" remarks="{}"/>"#,
        uid, cot_type, url, remarks
    )
}

/// Create both link and url elements for maximum compatibility
///
/// This includes both `<link>` (TAK protocol standard) and `<url>` (iTAK-friendly)
/// elements to ensure the link works across all TAK client versions.
///
/// # Example
///
/// ```
/// use takproto::helpers::hybrid_link;
///
/// let xml = hybrid_link("MARKER-001", "b-m-p-s-m", "https://example.com", "View Site");
/// ```
pub fn hybrid_link(uid: &str, cot_type: &str, url: &str, name: &str) -> String {
    format!(
        "{}\n{}",
        link_element(uid, cot_type, url, name),
        url_element(url, name)
    )
}

/// Create a remarks element
///
/// # Example
///
/// ```
/// use takproto::helpers::remarks;
///
/// let xml = remarks("This is a description");
/// // Returns: <remarks>This is a description</remarks>
/// ```
pub fn remarks(text: &str) -> String {
    format!("<remarks>{}</remarks>", text)
}

/// Create remarks with embedded URLs for manual copying (iTAK 2.12.3 compatible)
///
/// Since iTAK 2.12.3 doesn't support clickable `<url>` elements, this helper
/// creates a formatted remarks field with URLs that users can see and manually
/// copy/paste. iOS will detect URLs in text and allow long-press to copy/open.
///
/// # Example
///
/// ```
/// use takproto::helpers::remarks_with_urls;
///
/// let xml = remarks_with_urls(
///     "Mission Report",
///     &[("Full Report", "https://example.com/report")]
/// );
/// ```
pub fn remarks_with_urls(title: &str, urls: &[(&str, &str)]) -> String {
    let mut text = title.to_string();
    text.push_str("\n");

    for (label, url) in urls {
        text.push_str(&format!("\n{}: {}", label, url));
    }

    text.push_str("\n\n(Long-press URL to copy)");

    remarks(&text)
}

/// Create formatted remarks with multiple URLs and icons (iTAK compatible)
///
/// Creates a nicely formatted remarks field with icons and multiple URLs
/// that are easy to read and copy in iTAK.
///
/// # Example
///
/// ```
/// use takproto::helpers::remarks_with_formatted_urls;
///
/// let urls = vec![
///     ("📊", "Status Dashboard", "https://status.example.com"),
///     ("📞", "Contact Form", "https://contact.example.com"),
/// ];
/// let xml = remarks_with_formatted_urls("Resources", &urls);
/// ```
pub fn remarks_with_formatted_urls(title: &str, urls: &[(&str, &str, &str)]) -> String {
    let mut text = format!("{}\n", title);

    for (icon, label, url) in urls {
        text.push_str(&format!("\n{} {}:\n{}\n", icon, label, url));
    }

    text.push_str("\n(Long-press any URL to copy)");

    remarks(&text)
}

/// Create a color element
///
/// Colors in CoT use ARGB format as a signed 32-bit integer.
///
/// # Common Colors
///
/// * Red: -65536
/// * Green: -16711936
/// * Blue: -16776961
/// * Yellow: -256
/// * Black: -16777216
/// * White: -1
///
/// # Example
///
/// ```
/// use takproto::helpers::color;
///
/// let xml = color(-65536); // Red
/// // Returns: <color value="-65536"/>
/// ```
pub fn color(argb: i32) -> String {
    format!(r#"<color value="{}"/>"#, argb)
}

/// Create a URL-friendly UID from a domain name
///
/// Since iTAK 2.12.3 doesn't support clickable URLs in remarks,
/// the best workaround is to put the URL/domain in the marker UID itself.
/// This makes it visible on the map and easy to remember/type.
///
/// # Example
///
/// ```
/// use takproto::helpers::url_to_uid;
///
/// let uid = url_to_uid("https://www.rust-lang.org");
/// // Returns: "rust-lang.org"
/// ```
pub fn url_to_uid(url: &str) -> String {
    url.trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_start_matches("www.")
        .trim_end_matches('/')
        .to_string()
}

/// Common ARGB color values for CoT markers
pub mod colors {
    pub const RED: i32 = -65536;
    pub const GREEN: i32 = -16711936;
    pub const BLUE: i32 = -16776961;
    pub const YELLOW: i32 = -256;
    pub const BLACK: i32 = -16777216;
    pub const WHITE: i32 = -1;
    pub const ORANGE: i32 = -23296;
    pub const PURPLE: i32 = -8388480;
}

// ============================================================================
// Protobuf Detail Message Helpers
// ============================================================================

/// Create a Contact detail message
///
/// Used to specify contact information for a TAK entity, including
/// callsign (display name) and network endpoint.
///
/// # Arguments
///
/// * `callsign` - Display name/callsign for the contact (required)
/// * `endpoint` - Optional network endpoint (IP:port or protocol://host:port)
///
/// # Example
///
/// ```
/// use takproto::helpers::contact;
///
/// // Contact with endpoint
/// let c = contact("ALPHA-1", Some("192.168.1.100:4242"));
///
/// // Contact without endpoint
/// let c = contact("BRAVO-2", None);
/// ```
pub fn contact(callsign: &str, endpoint: Option<&str>) -> Contact {
    Contact {
        callsign: callsign.to_string(),
        endpoint: endpoint.unwrap_or("").to_string(),
    }
}

/// Create a Track detail message
///
/// Used to specify movement information for moving entities like
/// vehicles, aircraft, or people. Speed is in meters per second,
/// course is in degrees (0-360, where 0 is north).
///
/// # Arguments
///
/// * `speed_mps` - Speed in meters per second
/// * `course_degrees` - Course/heading in degrees (0-360, 0 = north)
///
/// # Example
///
/// ```
/// use takproto::helpers::track;
///
/// // Vehicle moving at 15 m/s (54 km/h) heading west (270°)
/// let t = track(15.0, 270.0);
/// ```
pub fn track(speed_mps: f64, course_degrees: f64) -> Track {
    Track {
        speed: speed_mps,
        course: course_degrees,
    }
}

/// Create a Group detail message
///
/// Used to organize entities into groups/teams with specific roles.
/// Common for military or team-based operations.
///
/// # Arguments
///
/// * `name` - Group/team name
/// * `role` - Role within the group
///
/// # Example
///
/// ```
/// use takproto::helpers::group;
///
/// let g = group("Team Alpha", "Team Leader");
/// let g2 = group("Recon Squad", "Scout");
/// ```
pub fn group(name: &str, role: &str) -> Group {
    Group {
        name: name.to_string(),
        role: role.to_string(),
    }
}

/// Create a Status detail message
///
/// Used to report device/entity status information, primarily battery level.
///
/// # Arguments
///
/// * `battery_percent` - Battery level as a percentage (0-100)
///
/// # Example
///
/// ```
/// use takproto::helpers::status;
///
/// let s = status(85); // 85% battery
/// ```
pub fn status(battery_percent: u32) -> Status {
    Status {
        battery: battery_percent,
    }
}

/// Create a Takv (TAK version) detail message
///
/// Used to identify the TAK client software and platform information.
///
/// # Arguments
///
/// * `device` - Device model/name
/// * `platform` - Platform name (e.g., "iOS", "Android", "Windows")
/// * `os` - Operating system version
/// * `version` - TAK application version
///
/// # Example
///
/// ```
/// use takproto::helpers::takv;
///
/// let t = takv("iPhone 14", "iOS", "17.0", "iTAK 2.12.3");
/// let t2 = takv("Samsung Galaxy", "Android", "13", "ATAK 4.8.1");
/// ```
pub fn takv(device: &str, platform: &str, os: &str, version: &str) -> Takv {
    Takv {
        device: device.to_string(),
        platform: platform.to_string(),
        os: os.to_string(),
        version: version.to_string(),
    }
}

/// Create a PrecisionLocation detail message
///
/// Used to specify the source/method of position determination for
/// high-precision applications.
///
/// # Arguments
///
/// * `geopointsrc` - Source of the geographic position (e.g., "GPS", "USER", "DTED")
/// * `altsrc` - Source of the altitude (e.g., "GPS", "DTED", "BARO")
///
/// # Example
///
/// ```
/// use takproto::helpers::precision_location;
///
/// // Position from GPS, altitude from barometric sensor
/// let p = precision_location("GPS", "BARO");
///
/// // Both from GPS
/// let p2 = precision_location("GPS", "GPS");
/// ```
pub fn precision_location(geopointsrc: &str, altsrc: &str) -> PrecisionLocation {
    PrecisionLocation {
        geopointsrc: geopointsrc.to_string(),
        altsrc: altsrc.to_string(),
    }
}

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

    #[test]
    fn test_url_element() {
        let result = url_element("https://example.com", "Test");
        assert!(result.contains(r#"url="https://example.com""#));
        assert!(result.contains(r#"name="Test""#));
    }

    #[test]
    fn test_color() {
        let result = color(colors::RED);
        assert_eq!(result, r#"<color value="-65536"/>"#);
    }

    #[test]
    fn test_remarks() {
        let result = remarks("Test message");
        assert_eq!(result, "<remarks>Test message</remarks>");
    }
}