asterisk-rs-agi 0.8.0

Async Rust FastAGI server for Asterisk Gateway Interface
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
use std::time::Duration;

use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};

use crate::command;
use crate::error::{AgiError, Result};
use crate::response::AgiResponse;

const MAX_RESPONSE_LINE_BYTES: usize = 8 * 1024;
const MAX_RESPONSE_BYTES: usize = 64 * 1024;
const DEFAULT_COMMAND_TIMEOUT: Duration = Duration::from_secs(30);

/// tracks whether a command round-trip is currently in progress
///
/// used to detect cancellation between write and read: if a caller drops
/// a `send_command` future after the write but before the read completes,
/// the state stays `InFlight` and the next call sees it immediately.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChannelState {
    /// ready to accept the next command
    Ready,
    /// write has been sent; waiting for the response line(s)
    InFlight,
    /// a previous failure left the stream in an undefined state
    Poisoned,
}

/// high-level interface for sending AGI commands over a connection
#[derive(Debug)]
pub struct AgiChannel {
    reader: BufReader<OwnedReadHalf>,
    writer: OwnedWriteHalf,
    hung_up: bool,
    state: ChannelState,
    command_timeout: Option<Duration>,
}

impl AgiChannel {
    /// create a new AGI channel from split TCP stream halves
    pub fn new(reader: BufReader<OwnedReadHalf>, writer: OwnedWriteHalf) -> Self {
        Self {
            reader,
            writer,
            hung_up: false,
            state: ChannelState::Ready,
            command_timeout: Some(DEFAULT_COMMAND_TIMEOUT),
        }
    }

    /// set or disable the deadline for each complete command round trip
    ///
    /// A conservative finite deadline is configured by default. Commands such
    /// as `WAIT FOR DIGIT -1`, `EXEC Dial`, and recording that legitimately wait
    /// longer can opt into a larger deadline or explicitly disable it. The deadline covers
    /// both the command write and complete response read. If it expires, the
    /// channel is poisoned because the late response cannot be correlated
    /// safely with another command.
    pub fn set_command_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
        if timeout.is_some_and(|timeout| timeout.is_zero()) {
            return Err(AgiError::InvalidArgument {
                details: "command timeout must be greater than zero".to_owned(),
            });
        }
        self.command_timeout = timeout;
        Ok(())
    }

    /// return the configured command deadline, or `None` when disabled
    pub fn command_timeout(&self) -> Option<Duration> {
        self.command_timeout
    }

    /// send a raw command string and parse the response
    ///
    /// # cancel safety
    ///
    /// this function is **not** cancel-safe. dropping the future after the write
    /// but before the read completes leaves an unread response in the buffer.
    /// subsequent calls will observe `ChannelState::InFlight` and return
    /// `AgiError::CommandInFlight` to prevent reading stale data.
    ///
    /// the command should already be formatted with a trailing newline.
    pub async fn send_command(&mut self, command: &str) -> Result<AgiResponse> {
        if self.hung_up {
            return Err(AgiError::ChannelHungUp);
        }
        match self.state {
            ChannelState::InFlight => return Err(AgiError::CommandInFlight),
            ChannelState::Poisoned => return Err(AgiError::ChannelPoisoned),
            ChannelState::Ready => {}
        }

        if command.contains('\r')
            || !command.ends_with('\n')
            || command[..command.len() - 1].contains('\n')
        {
            return Err(AgiError::InvalidArgument {
                details: "raw command must contain exactly one trailing newline".to_owned(),
            });
        }
        if command.len() > command::MAX_COMMAND_BYTES {
            return Err(AgiError::InvalidArgument {
                details: format!(
                    "AGI command exceeds the {}-byte limit",
                    command::MAX_COMMAND_BYTES
                ),
            });
        }

        // mark in-flight before write so that a cancellation between write and
        // read is visible to the next caller
        self.state = ChannelState::InFlight;

        match self.command_timeout {
            Some(timeout) => {
                match tokio::time::timeout(timeout, self.command_round_trip(command)).await {
                    Ok(result) => result,
                    Err(_) => {
                        self.state = ChannelState::Poisoned;
                        Err(AgiError::CommandTimeout { elapsed: timeout })
                    }
                }
            }
            None => self.command_round_trip(command).await,
        }
    }

    async fn command_round_trip(&mut self, command: &str) -> Result<AgiResponse> {
        if let Err(e) = self.writer.write_all(command.as_bytes()).await {
            self.state = ChannelState::Poisoned;
            return Err(AgiError::Io(e));
        }
        if let Err(e) = self.writer.flush().await {
            self.state = ChannelState::Poisoned;
            return Err(AgiError::Io(e));
        }

        let mut line = String::new();
        let bytes_read = self.read_bounded_line(&mut line).await?;

        if bytes_read == 0 {
            self.hung_up = true;
            self.state = ChannelState::Poisoned;
            return Err(AgiError::ChannelHungUp);
        }

        // 520 with a dash is a multiline response — drain all continuation
        // lines until the terminating `520 End of proper usage.` line
        if let Some(stripped) = line.strip_prefix("520-") {
            let first = stripped.trim().to_owned();
            let mut usage = first;
            let mut response_bytes = line.len();
            loop {
                let mut next = String::new();
                let n = self.read_bounded_line(&mut next).await?;
                if n == 0 {
                    self.hung_up = true;
                    self.state = ChannelState::Poisoned;
                    return Err(AgiError::ChannelHungUp);
                }
                response_bytes = response_bytes.saturating_add(n);
                if response_bytes > MAX_RESPONSE_BYTES {
                    self.state = ChannelState::Poisoned;
                    return Err(AgiError::ResponseTooLarge {
                        limit: MAX_RESPONSE_BYTES,
                    });
                }
                let trimmed = next.trim();
                if trimmed == "520 End of proper usage." {
                    break;
                }
                if !usage.is_empty() {
                    usage.push('\n');
                }
                usage.push_str(trimmed);
            }
            self.state = ChannelState::Ready;
            return Err(AgiError::CommandFailed {
                code: 520,
                message: usage,
            });
        }

        let response = match AgiResponse::parse(&line) {
            Ok(r) => r,
            Err(e) => {
                self.state = ChannelState::Poisoned;
                return Err(e);
            }
        };

        // 511 means the channel is dead
        if response.code == 511 {
            self.hung_up = true;
            self.state = ChannelState::Poisoned;
            return Err(AgiError::ChannelHungUp);
        }

        self.state = ChannelState::Ready;
        Ok(response)
    }

    async fn read_bounded_line(&mut self, line: &mut String) -> Result<usize> {
        let bytes_read = match (&mut self.reader)
            .take((MAX_RESPONSE_LINE_BYTES + 1) as u64)
            .read_line(line)
            .await
        {
            Ok(n) => n,
            Err(error) => {
                self.state = ChannelState::Poisoned;
                return Err(AgiError::Io(error));
            }
        };

        if line.len() > MAX_RESPONSE_LINE_BYTES {
            self.state = ChannelState::Poisoned;
            return Err(AgiError::ResponseTooLarge {
                limit: MAX_RESPONSE_LINE_BYTES,
            });
        }
        if bytes_read != 0 && !line.ends_with('\n') {
            self.state = ChannelState::Poisoned;
            return Err(AgiError::InvalidResponse {
                raw: "response line ended without a newline".to_owned(),
            });
        }
        Ok(bytes_read)
    }

    /// answer the channel
    pub async fn answer(&mut self) -> Result<AgiResponse> {
        let cmd = command::format_command(command::ANSWER, &[])?;
        self.send_command(&cmd).await
    }

    /// hang up the channel, optionally specifying which channel to hang up
    pub async fn hangup(&mut self, channel: Option<&str>) -> Result<AgiResponse> {
        let cmd = match channel {
            Some(ch) => command::format_command(command::HANGUP, &[ch])?,
            None => command::format_command(command::HANGUP, &[])?,
        };
        self.send_command(&cmd).await
    }

    /// stream a sound file, allowing the caller to interrupt with escape digits
    pub async fn stream_file(
        &mut self,
        filename: &str,
        escape_digits: &str,
    ) -> Result<AgiResponse> {
        let cmd = command::format_command(command::STREAM_FILE, &[filename, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// play a prompt and collect DTMF digits
    pub async fn get_data(
        &mut self,
        filename: &str,
        timeout_ms: u64,
        max_digits: u32,
    ) -> Result<AgiResponse> {
        let timeout = timeout_ms.to_string();
        let digits = max_digits.to_string();
        let cmd = command::format_command(command::GET_DATA, &[filename, &timeout, &digits])?;
        self.send_command(&cmd).await
    }

    /// say a digit string with escape digits
    pub async fn say_digits(&mut self, digits: &str, escape_digits: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SAY_DIGITS, &[digits, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// say a number with escape digits
    pub async fn say_number(&mut self, number: i64, escape_digits: &str) -> Result<AgiResponse> {
        let num = number.to_string();
        let cmd = command::format_command(command::SAY_NUMBER, &[&num, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// set a channel variable
    pub async fn set_variable(&mut self, name: &str, value: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SET_VARIABLE, &[name, value])?;
        self.send_command(&cmd).await
    }

    /// get a channel variable
    pub async fn get_variable(&mut self, name: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::GET_VARIABLE, &[name])?;
        self.send_command(&cmd).await
    }

    /// execute an asterisk application
    pub async fn exec(&mut self, application: &str, args: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::EXEC, &[application, args])?;
        self.send_command(&cmd).await
    }

    /// wait for a DTMF digit, -1 for infinite Asterisk-side timeout
    ///
    /// an explicitly configured channel command deadline still applies
    pub async fn wait_for_digit(&mut self, timeout_ms: i64) -> Result<AgiResponse> {
        let timeout = timeout_ms.to_string();
        let cmd = command::format_command(command::WAIT_FOR_DIGIT, &[&timeout])?;
        self.send_command(&cmd).await
    }

    /// get the status of a channel
    pub async fn channel_status(&mut self, channel: Option<&str>) -> Result<AgiResponse> {
        let cmd = match channel {
            Some(ch) => command::format_command(command::CHANNEL_STATUS, &[ch])?,
            None => command::format_command(command::CHANNEL_STATUS, &[])?,
        };
        self.send_command(&cmd).await
    }

    /// send a verbose message to the asterisk console
    pub async fn verbose(&mut self, message: &str, level: u8) -> Result<AgiResponse> {
        let lvl = level.to_string();
        let cmd = command::format_command(command::VERBOSE, &[message, &lvl])?;
        self.send_command(&cmd).await
    }

    /// set the caller id for the current channel
    pub async fn set_callerid(&mut self, callerid: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SET_CALLERID, &[callerid])?;
        self.send_command(&cmd).await
    }

    /// get a value from the asterisk database
    pub async fn database_get(&mut self, family: &str, key: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::DATABASE_GET, &[family, key])?;
        self.send_command(&cmd).await
    }

    /// set a value in the asterisk database
    pub async fn database_put(
        &mut self,
        family: &str,
        key: &str,
        value: &str,
    ) -> Result<AgiResponse> {
        let cmd = command::format_command(command::DATABASE_PUT, &[family, key, value])?;
        self.send_command(&cmd).await
    }

    /// delete a key from the asterisk database
    pub async fn database_del(&mut self, family: &str, key: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::DATABASE_DEL, &[family, key])?;
        self.send_command(&cmd).await
    }

    /// delete a family or key tree from the asterisk database
    pub async fn database_deltree(
        &mut self,
        family: &str,
        key: Option<&str>,
    ) -> Result<AgiResponse> {
        let cmd = match key {
            Some(k) => command::format_command(command::DATABASE_DELTREE, &[family, k])?,
            None => command::format_command(command::DATABASE_DELTREE, &[family])?,
        };
        self.send_command(&cmd).await
    }

    /// stream file with ability to control (pause, rewind, fast forward)
    pub async fn control_stream_file(
        &mut self,
        filename: &str,
        escape_digits: &str,
        skipms: Option<i64>,
        ff_char: Option<&str>,
        rew_char: Option<&str>,
        pause_char: Option<&str>,
    ) -> Result<AgiResponse> {
        let skip = skipms.unwrap_or(3000).to_string();
        let ff = ff_char.unwrap_or("");
        let rew = rew_char.unwrap_or("");
        let pause = pause_char.unwrap_or("");
        let cmd = command::format_command(
            command::CONTROL_STREAM_FILE,
            &[filename, escape_digits, &skip, ff, rew, pause],
        )?;
        self.send_command(&cmd).await
    }

    /// get a full variable expression, evaluating functions and expressions
    pub async fn get_full_variable(
        &mut self,
        expression: &str,
        channel: Option<&str>,
    ) -> Result<AgiResponse> {
        let cmd = match channel {
            Some(ch) => command::format_command(command::GET_FULL_VARIABLE, &[expression, ch])?,
            None => command::format_command(command::GET_FULL_VARIABLE, &[expression])?,
        };
        self.send_command(&cmd).await
    }

    /// stream file with playback offset, allowing the caller to interrupt with escape digits
    pub async fn get_option(
        &mut self,
        filename: &str,
        escape_digits: &str,
        timeout_ms: Option<i64>,
    ) -> Result<AgiResponse> {
        let cmd = match timeout_ms {
            Some(t) => {
                let ts = t.to_string();
                command::format_command(command::GET_OPTION, &[filename, escape_digits, &ts])?
            }
            None => command::format_command(command::GET_OPTION, &[filename, escape_digits])?,
        };
        self.send_command(&cmd).await
    }

    /// execute a dialplan subroutine
    pub async fn gosub(
        &mut self,
        context: &str,
        extension: &str,
        priority: &str,
        args: Option<&str>,
    ) -> Result<AgiResponse> {
        let cmd = match args {
            Some(a) => command::format_command(command::GOSUB, &[context, extension, priority, a])?,
            None => command::format_command(command::GOSUB, &[context, extension, priority])?,
        };
        self.send_command(&cmd).await
    }

    /// do nothing, used for testing
    pub async fn noop(&mut self) -> Result<AgiResponse> {
        let cmd = command::format_command(command::NOOP, &[])?;
        self.send_command(&cmd).await
    }

    /// receive a character from the connected channel
    pub async fn receive_char(&mut self, timeout_ms: i64) -> Result<AgiResponse> {
        let timeout = timeout_ms.to_string();
        let cmd = command::format_command(command::RECEIVE_CHAR, &[&timeout])?;
        self.send_command(&cmd).await
    }

    /// receive a text message from the connected channel
    pub async fn receive_text(&mut self, timeout_ms: i64) -> Result<AgiResponse> {
        let timeout = timeout_ms.to_string();
        let cmd = command::format_command(command::RECEIVE_TEXT, &[&timeout])?;
        self.send_command(&cmd).await
    }

    /// record audio to a file
    pub async fn record_file(
        &mut self,
        filename: &str,
        format: &str,
        escape_digits: &str,
        timeout_ms: i64,
        beep: bool,
        silence: Option<u32>,
    ) -> Result<AgiResponse> {
        let timeout = timeout_ms.to_string();
        let mut args = vec![filename, format, escape_digits, &timeout];
        let beep_str;
        if beep {
            beep_str = "beep".to_string();
            args.push(&beep_str);
        }
        let silence_str;
        if let Some(s) = silence {
            silence_str = format!("s={s}");
            args.push(&silence_str);
        }
        let cmd = command::format_command(command::RECORD_FILE, &args)?;
        self.send_command(&cmd).await
    }

    /// say an alphabetic string with escape digits
    pub async fn say_alpha(&mut self, text: &str, escape_digits: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SAY_ALPHA, &[text, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// say a date (unix timestamp) with escape digits
    pub async fn say_date(&mut self, date: i64, escape_digits: &str) -> Result<AgiResponse> {
        let d = date.to_string();
        let cmd = command::format_command(command::SAY_DATE, &[&d, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// say a date and time (unix timestamp) with escape digits
    pub async fn say_datetime(
        &mut self,
        datetime: i64,
        escape_digits: &str,
        format: Option<&str>,
        timezone: Option<&str>,
    ) -> Result<AgiResponse> {
        let dt = datetime.to_string();
        let mut args = vec![dt.as_str(), escape_digits];
        let fmt;
        if let Some(f) = format {
            fmt = f.to_string();
            args.push(&fmt);
            if let Some(tz) = timezone {
                args.push(tz);
            }
        }
        let cmd = command::format_command(command::SAY_DATETIME, &args)?;
        self.send_command(&cmd).await
    }

    /// say a string phonetically with escape digits
    pub async fn say_phonetic(&mut self, text: &str, escape_digits: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SAY_PHONETIC, &[text, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// say a time (unix timestamp) with escape digits
    pub async fn say_time(&mut self, time: i64, escape_digits: &str) -> Result<AgiResponse> {
        let t = time.to_string();
        let cmd = command::format_command(command::SAY_TIME, &[&t, escape_digits])?;
        self.send_command(&cmd).await
    }

    /// send an image to the connected channel
    pub async fn send_image(&mut self, image: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SEND_IMAGE, &[image])?;
        self.send_command(&cmd).await
    }

    /// send text to the connected channel
    pub async fn send_text(&mut self, text: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SEND_TEXT, &[text])?;
        self.send_command(&cmd).await
    }

    /// set the auto-hangup timer in seconds (0 to disable)
    pub async fn set_autohangup(&mut self, seconds: u32) -> Result<AgiResponse> {
        let s = seconds.to_string();
        let cmd = command::format_command(command::SET_AUTOHANGUP, &[&s])?;
        self.send_command(&cmd).await
    }

    /// set the dialplan context for continuation after agi completes
    pub async fn set_context(&mut self, context: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SET_CONTEXT, &[context])?;
        self.send_command(&cmd).await
    }

    /// set the dialplan extension for continuation after agi completes
    pub async fn set_extension(&mut self, extension: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SET_EXTENSION, &[extension])?;
        self.send_command(&cmd).await
    }

    /// enable or disable music on hold
    pub async fn set_music(&mut self, enabled: bool, class: Option<&str>) -> Result<AgiResponse> {
        let on_off = if enabled { "on" } else { "off" };
        let cmd = match class {
            Some(c) => command::format_command(command::SET_MUSIC, &[on_off, c])?,
            None => command::format_command(command::SET_MUSIC, &[on_off])?,
        };
        self.send_command(&cmd).await
    }

    /// set the dialplan priority for continuation after agi completes
    pub async fn set_priority(&mut self, priority: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SET_PRIORITY, &[priority])?;
        self.send_command(&cmd).await
    }

    /// create a speech recognition object
    pub async fn speech_create(&mut self, engine: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_CREATE, &[engine])?;
        self.send_command(&cmd).await
    }

    /// destroy the current speech recognition object
    pub async fn speech_destroy(&mut self) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_DESTROY, &[])?;
        self.send_command(&cmd).await
    }

    /// activate a loaded grammar for recognition
    pub async fn speech_activate_grammar(&mut self, grammar_name: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_ACTIVATE_GRAMMAR, &[grammar_name])?;
        self.send_command(&cmd).await
    }

    /// deactivate a grammar
    pub async fn speech_deactivate_grammar(&mut self, grammar_name: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_DEACTIVATE_GRAMMAR, &[grammar_name])?;
        self.send_command(&cmd).await
    }

    /// load a grammar from a file
    pub async fn speech_load_grammar(
        &mut self,
        grammar_name: &str,
        path: &str,
    ) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_LOAD_GRAMMAR, &[grammar_name, path])?;
        self.send_command(&cmd).await
    }

    /// unload a previously loaded grammar
    pub async fn speech_unload_grammar(&mut self, grammar_name: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_UNLOAD_GRAMMAR, &[grammar_name])?;
        self.send_command(&cmd).await
    }

    /// play a prompt and perform speech recognition
    pub async fn speech_recognize(
        &mut self,
        prompt: &str,
        timeout_ms: i64,
        offset: Option<i64>,
    ) -> Result<AgiResponse> {
        let t = timeout_ms.to_string();
        let cmd = match offset {
            Some(o) => {
                let os = o.to_string();
                command::format_command(command::SPEECH_RECOGNIZE, &[prompt, &t, &os])?
            }
            None => command::format_command(command::SPEECH_RECOGNIZE, &[prompt, &t])?,
        };
        self.send_command(&cmd).await
    }

    /// set a speech engine setting
    pub async fn speech_set(&mut self, name: &str, value: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::SPEECH_SET, &[name, value])?;
        self.send_command(&cmd).await
    }

    /// enable or disable tdd mode on the channel
    pub async fn tdd_mode(&mut self, mode: &str) -> Result<AgiResponse> {
        let cmd = command::format_command(command::TDD_MODE, &[mode])?;
        self.send_command(&cmd).await
    }

    /// break out of async agi
    pub async fn asyncagi_break(&mut self) -> Result<AgiResponse> {
        let cmd = command::format_command(command::ASYNCAGI_BREAK, &[])?;
        self.send_command(&cmd).await
    }
}