Page 239 - Asterisk™: The Future of Telephony
P. 239
As we explained earlier, Asterisk sends a group of variables to the AGI program at
startup. This loop simply takes all of these variables and stores them in the hash named
AGI. They can be used later in the program or simply ignored, but they should always
be read from STDIN before continuing on with the logic of the program.
print STDERR "AGI Environment Dump:\n";
foreach my $i (sort keys %AGI) {
print STDERR " -- $i = $AGI{$i}\n";
}
This loop simply writes each of the values that we stored in the AGI hash to STDERR. This
is useful for debugging the AGI script, as STDERR is printed to the Asterisk console. †
sub checkresult {
my ($res) = @_;
my $retval;
$tests++;
chomp $res;
if ($res =~ /^200/) {
$res =~ /result=(-?\d+)/;
if (!length($1)) {
print STDERR "FAIL ($res)\n";
$fail++;
} else {
print STDERR "PASS ($1)\n";
$pass++;
}
} else {
print STDERR "FAIL (unexpected result '$res')\n";
$fail++;
}
This subroutine reads in the result of an AGI command from Asterisk and decodes the
result to determine whether the command passes or fails.
Now that the preliminaries are out of the way, we can get to the core logic of the AGI
script:
print STDERR "1. Testing 'sendfile'...";
print "STREAM FILE beep \"\"\n";
my $result = <STDIN>;
&checkresult($result);
This first test shows how to use the STREAM FILE command. The STREAM FILE command
tells Asterisk to play a sound file to the caller, just as the Background() application does.
In this case, we’re telling Asterisk to play a file called beep.gsm. ‡
† Actually, to the first spawned Asterisk console (i.e., the first instance of Asterisk called with the -c option).
If safe_asterisk was used to start Asterisk, the first Asterisk console will be on TTY9, which means that you
will not be able to view AGI errors remotely.
‡ Asterisk automatically selects the best format, based on translation cost and availability, so the file extension
is never used in the function.
Writing AGI Scripts in Perl | 211