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
//! # TrackAudio client library
//!
//! `trackaudio` is a Rust client library for interacting with [TrackAudio](https://github.com/pierr3/TrackAudio),
//! a modern voice communication application for [VATSIM](https://vatsim.net/) air traffic controllers.
//!
//! This crate provides a high-level, async API for controlling TrackAudio programmatically via
//! its [WebSocket interface](https://github.com/pierr3/TrackAudio/wiki/SDK-documentation), allowing
//! you to build custom integrations, automation tools, or alternative user interfaces.
//!
//! ## Features
//!
//! - **Async/await API**: Built on Tokio for efficient async I/O
//! - **Type-safe commands and events**: Strongly-typed message protocol
//! - **Request-response pattern**: High-level API for commands that expect responses
//! - **Event streaming**: Subscribe to real-time events from TrackAudio
//! - **Automatic reconnection**: Resilient WebSocket connections with exponential backoff
//! - **Thread-safe**: Client can be safely shared across threads
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use trackaudio::{Command, Event, TrackAudioClient};
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! // Connect to TrackAudio (defaults to ws://127.0.0.1:49080/ws)
//! let client = TrackAudioClient::connect_default().await?;
//!
//! // Subscribe to events
//! let mut events = client.subscribe();
//!
//! // Send a command
//! client.send(Command::PttPressed).await?;
//!
//! // Listen for events
//! while let Ok(event) = events.recv().await {
//! match event {
//! Event::TxBegin(_) => println!("Started transmitting"),
//! Event::RxBegin(rx) => println!("Receiving from {}", rx.callsign),
//! _ => {}
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ## High-level API
//!
//! For common operations you can use [`TrackAudioApi`], which wraps [`TrackAudioClient`] and
//! provides typed convenience methods based on the [`Request`](messages::Request) pattern:
//!
//! ```rust,no_run
//! use std::time::Duration;
//! use trackaudio::TrackAudioClient;
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! let client = TrackAudioClient::connect_default().await?;
//! let api = client.api();
//!
//! // Add a station and wait for its initial state
//! let station = api.add_station("LOVV_CTR", Some(Duration::from_secs(5))).await?;
//! println!("Added station: {station:?}");
//!
//! // Change the main volume
//! let volume = api.change_main_volume(-20, None).await?;
//! println!("Changed main volume to {volume}");
//!
//! Ok(())
//! }
//! ```
//!
//! ### Choosing between low-level and high-level APIs
//!
//! - Use [`TrackAudioClient`] when you want **full control**:
//! - subscribe to the raw [`Event`] stream
//! - send arbitrary [`Command`]s
//! - implement your own request/response logic
//!
//! - Use [`TrackAudioApi`] for **common operations** with less boilerplate:
//! - add/remove stations
//! - query station states
//! - adjust volumes and other simple settings
//! - transmit on all active frequencies
//!
//! ## Architecture
//!
//! The library is organized around three main parts:
//!
//! ### [`TrackAudioClient`]
//!
//! The core WebSocket client that handles connection management, command sending,
//! and event distribution. Use this for low-level control or when you need to
//! work directly with the command/event protocol.
//!
//! ### [`TrackAudioApi`]
//!
//! A high-level API wrapper that provides convenient methods for common operations
//! with built-in request-response matching and timeout handling.
//!
//! ### Messages
//!
//! - [`Command`]: Commands you send to TrackAudio (PTT, add station, set volume, etc.)
//! - [`Event`]: Events emitted by TrackAudio (station updates, RX/TX state changes, etc.)
//! - [`Request`](messages::Request): Trait for typed request-response patterns
//!
//! ## Configuration
//!
//! Use [`TrackAudioConfig`] to control connection parameters and internal behavior:
//!
//! IPv4 and `ws://` are currently supported; IPv6 and `wss://` are not. Check the documentation of
//! [`TrackAudioConfig`] for more details on supported URL variants.
//!
//! If you're simply trying to connect to the default TrackAudio instance on your local machine,
//! you can use [`TrackAudioClient::connect_default`] to create a client with the default configuration:
//!
//! ```rust,no_run
//! use trackaudio::TrackAudioClient;
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! let client = TrackAudioClient::connect_default().await?;
//!
//! Ok(())
//! }
//! ```
//!
//! If you need to customize the connection parameters, you can use [`TrackAudioClient::connect`].
//!
//! Connecting to a remote TrackAudio instance without modifying additional config values can be
//! performed via [`TrackAudioClient::connect_url`]:
//!
//! ```rust,no_run
//! use trackaudio::{TrackAudioClient, TrackAudioConfig};
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! let config = TrackAudioConfig::new("192.168.1.69:49080")?
//! .with_capacity(512, 512)
//! .with_ping_interval(Duration::from_secs(10));
//!
//! let client = TrackAudioClient::connect(config).await?;
//! Ok(())
//! }
//! ```
//!
//! ## Reconnection
//!
//! The client automatically reconnects on connection loss with exponential backoff.
//! This is enabled by default and can be configured:
//!
//! ```rust,no_run
//! use trackaudio::{TrackAudioClient, TrackAudioConfig, ConnectionState, ClientEvent, Event};
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! let config = TrackAudioConfig::default()
//! .with_auto_reconnect(true) // Enabled by default
//! .with_max_reconnect_attempts(Some(10)) // None = infinite retries
//! .with_backoff_config(
//! Duration::from_secs(1), // Initial backoff
//! Duration::from_secs(60), // Max backoff
//! 2.0, // Multiplier
//! );
//!
//! let client = TrackAudioClient::connect(config).await?;
//!
//! // Monitor connection state changes
//! let mut events = client.subscribe();
//! while let Ok(event) = events.recv().await {
//! if let Event::Client(ClientEvent::ConnectionStateChanged(state)) = event {
//! match state {
//! ConnectionState::Disconnected { reason } => {
//! println!("Disconnected: {reason}");
//! }
//! ConnectionState::Reconnecting { attempt, next_delay } => {
//! println!("Reconnecting (attempt {attempt}) in {next_delay:?}...");
//! }
//! ConnectionState::Connected => {
//! println!("Connected!");
//! }
//! _ => {}
//! }
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! You can also manually trigger reconnection:
//!
//! ```rust,no_run
//! use trackaudio::TrackAudioClient;
//! async fn example(client: TrackAudioClient) -> trackaudio::Result<()> {
//! client.reconnect()?;
//! Ok(())
//! }
//! ```
//!
//! ## Request/response pattern
//!
//! Some commands support a request/response style interaction by implementing the [`Request`](messages::Request) trait.
//! You can send these requests directly via [`TrackAudioClient::request`]:
//!
//! ```rust,no_run
//! use std::time::Duration;
//! use trackaudio::TrackAudioClient;
//! use trackaudio::messages::commands::GetStationStates;
//!
//! #[tokio::main]
//! async fn main() -> trackaudio::Result<()> {
//! let client = TrackAudioClient::connect_default().await?;
//!
//! // Get a snapshot of all station states
//! let states = client
//! .request(GetStationStates, Some(Duration::from_secs(5)))
//! .await?;
//! println!("We have {} stations", states.len());
//!
//! Ok(())
//! }
//! ```
//!
//! The [`Request`](messages::Request) implementation ties a concrete [`Command`] (e.g., [`GetStationStates`](messages::commands::GetStationStates)
//! to the matching [`Event`] returned by TrackAudio, and converts them into a typed response
//! (e.g., `Vec<StationState>`).
//!
//! ## Working with frequencies
//!
//! TrackAudio returns and expects all frequencies to be in Hertz, however that seem a bit cumbersome
//! to work with. The [`Frequency`] type stores values in Hertz internally but offers helpers for
//! Hz, kHz, and MHz:
//!
//! ```rust
//! use trackaudio::Frequency;
//!
//! let a = Frequency::from_hz(132_600_000);
//! let b = Frequency::from_khz(132_600);
//! let c = Frequency::from_mhz(132.600);
//!
//! assert_eq!(a, b);
//! assert_eq!(b, c);
//! assert_eq!(a.as_mhz(), 132.600);
//!
//! // Convenient conversion to/from MHz as f64
//! let freq: Frequency = 132.600_f64.into();
//! let mhz: f64 = freq.into();
//! assert_eq!(freq.as_mhz(), mhz);
//!
//! // Convenient conversion to/from Hz as u64
//! let freq: Frequency = 132_600_000_u64.into();
//! let hz: u64 = freq.into();
//! assert_eq!(freq.as_hz(), hz);
//! ```
//!
//! ## Error Handling
//!
//! All operations return a [`Result<T>`](Result) type with [`TrackAudioError`] variants:
//!
//! ```rust,no_run
//! use trackaudio::{TrackAudioClient, TrackAudioError};
//!
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! match TrackAudioClient::connect_default().await {
//! Ok(client) => { /* use client */ },
//! Err(TrackAudioError::WebSocket(e)) => {
//! eprintln!("Connection failed: {}", e);
//! },
//! Err(TrackAudioError::Timeout) => {
//! eprintln!("Connection timed out");
//! },
//! Err(e) => {
//! eprintln!("Other error: {}", e);
//! }
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Client-emitted events
//!
//! In addition to events originating from TrackAudio itself, the client can inject internal events
//! via the [`Event::Client`] variant. These carry a [`ClientEvent`] and are used to report issues such as:
//!
//! - Connection loss
//! - Failed command transmission
//! - Event deserialization errors
//!
//! You receive them on the same broadcast channel as all other events.
//!
//! ## Features
//!
//! - `tracing`: integrate with the [`tracing`](https://docs.rs/tracing) crate
//! and emit spans for key operations (connect, send, request, etc.). Enabled by default.
//!
//! ## External Resources
//!
//! - [TrackAudio GitHub](https://github.com/pierr3/TrackAudio)
//! - [TrackAudio SDK Documentation](https://github.com/pierr3/TrackAudio/wiki/SDK-documentation)
//! - [VATSIM](https://vatsim.net/)
pub use TrackAudioApi;
pub use TrackAudioClient;
pub use TrackAudioConfig;
pub use ;
/// The crate's `Result` type, used throughout the library to indicate success or failure.
///
/// This type is a convenient alias for `std::result::Result` where the error type is
/// [`TrackAudioError`] and is used by all public API functions as relevant.
///
/// # Type Parameters
/// - `T`: The type of the success value contained in the `Result`.
pub type Result<T> = Result;
/// The `TrackAudioError` enum represents various errors that can occur while using this crate.