0% found this document useful (0 votes)
342 views

Asterisk Gateway Interface (AGI) : - CHAPTER 21

The document discusses different methods for implementing call control in Asterisk using external programming languages. It describes Asterisk Gateway Interface (AGI), which allows developing call control applications in other languages. It then summarizes various AGI variants: process-based AGI runs scripts locally, FastAGI runs them via TCP for better scalability, while Enhanced AGI adds an audio stream.

Uploaded by

Juan Arias
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
342 views

Asterisk Gateway Interface (AGI) : - CHAPTER 21

The document discusses different methods for implementing call control in Asterisk using external programming languages. It describes Asterisk Gateway Interface (AGI), which allows developing call control applications in other languages. It then summarizes various AGI variants: process-based AGI runs scripts locally, FastAGI runs them via TCP for better scalability, while Enhanced AGI adds an audio stream.

Uploaded by

Juan Arias
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

________________________________ CHAPTER 21

Asterisk Gateway Interface (AGI)


Caffeine. Thegateway drug.
Eddie Vedder
The Asterisk dialplan has evolved into a simple yet powerful programming interface
for cali handling. However, many people, especially those with a prior programming
background, still prefer implementing their custom cali handling in a different pro
gramming language. Using another programming language may also allow you to uti-
lize existing code for integration with other systems. The Asterisk Gateway Interface
(AGI) allows the development of first-party cali control in the programming language
of your choice. If you are not interested in implementing cali control outside of the
native Asterisk dialplan, you may safely skip this chapter.
Quick Start
This section gives a quick example of using the AGI. First, add the following line
to /etc/asterisk/extensions.conf:
ext en => 500, l , AGI ( hel l o- worl d. sh)
Next, create a hello-world.sh script in /var/lib/asterisk/agi-bin/, as shown in Exam
ple 21-1.
Example21-1. A sampleAGI script, hello-world.sh
#! / bi n/ bash
#Consume al l vari abl es sent by Ast eri sk
whi l e read VAR && [ -n ${VAR} ] ; do : ; done
#Answer t he cal i ,
echo "ANSWER"
read RESPONSE
#Say the l et t ers of "Hel i o Worl d"
475
echo SAY ALPHA "Helio World.........
read RESPONSE
exi t O
Now, cali extensin 500 with AGI debugging turned on and listen to Allison spell out
Helio World:
*CLI > agi set debug on
AGI Debuggi ng Enabl ed
-- Execut i ng [ 500@phones: l ] AGI ( "SI P/ 0004F2060EB4- 00000009",
"hel l o- worl d. sh") i n new stack
-- Launched AGI Scri pt / var/ l i b/ ast eri sk/ agi - bi n/ hel l o- worl d. sh
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060EB4- 00000009 >AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060E B4- 00000009 >AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Tx
<SI P/ 0004F2060EB4- 00000009>AGI Rx
<SI P/ 0004F 2060EB4- 00000009>AGI Tx
<SI P/ 0004F 2060EB4- 00000009 >AGI Rx
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4-00000009> Pl ayi ng
-- <SI P/ 0004F2060EB4- 00000009> Pl ayi ng
agi _request : hel l o- worl d. sh
agi _channel : SI P/ 0004F2060EB4- 00000009
agi _l anguage: en
agi _type: SI P
agi _uni quei d: 1284382003. 9
agi _versi on: l . 8. 0- bet a4
agi _cal l eri d: 2563619899
agi _cal l eri dname: Russel l Bryant
agi _cal l i ngpres: 0
agi _cal l i ngani 2: 0
agi _cal l i ngt on: 0
agi _cal l i ngt ns: 0
agi _dni d: 7010
agi _rdni s: unknown
agi _cont ext : phones
agi _ext ensi on: 500
agi _pri ori t y: 1
agi _enhanced: 0. 0
agi _account code:
agi _t hreadi d: 140071216785168
ANSWER
200 r esul t o
SAY ALPHA "Hel i o Wor l d. . .
l etters/ h. gsm' ( l anguage ' en' )
l et t ers/ e. gsm' ( l anguage ' en' )
l et t ers/ l . gsm' ( l anguage ' en' )
l et t ers/ l . gsm' ( l anguage ' en' )
l etters/ o. gsm' ( l anguage ' en' )
l et t ers/ space. gsm' ( l anguage ' en' )
l etters/ w. gsm' ( l anguage ' en' )
l et t ers/ o. gsm' ( l anguage ' en' )
l etters/ r. gsm' ( l anguage ' en' )
l et t ers/ l . gsm' ( l anguage ' en' )
l etters/ d. gsm' ( l anguage ' en' ) -- <SI P/ 0004F2060E B4- 00000009> Pl ayi ng
<SI P/ 0004F2060EB4- 00000009>AGI Tx >> 200 resul t =0
-- <SI P/ 0004F2060EB4- 00000009>AGI Scri pt hel l o- worl d. sh compl et ed, ret urni ng 0
476 | Chapter 21: Asterisk Gateway Interface (AGI)
AGI Variants
There are a few variants of AGI that differ primarily in the method used to communicate
with Asterisk. It is good to be aware of all of the options so you can make the best choice
based on the needs of your application.
Process-Based AGI
Process-based AGI is the simplest variant of AGI. The quick-start example at the
beginning of this chapter was an example of a process-based AGI script. The AGI script
is invoked by using the AGI() application from the Asterisk dialplan. The application
to run is specified as the first argument to AGI(). Unless a full path is specified, the
application is expected to exist in the /var/lib/asterisk/agi-bin/ directory. Arguments to
be passed to your AGI application can be specified as additional arguments to the
AGI() application in the Asterisk dialplan. The syntax is:
AGI (comand[, argl [, arg2 [,...]]])
0 **
Vr-
t\
>!' 4
Ensure that your application has the proper permissions set such that
the user the Asterisk process is running as has permissions to execute
TK; it. Otherwise, AGI ( ) will fail.
Once Asterisk executes your AGI application, communication between Asterisk and
your application will take place over stdin and stdout. More details about this commu
nication will be covered in AGI Communication Overview on page 480. For more
details about invoking AGI() from the dialplan, check the documentation built into
Asterisk:
*CLI > core showappl i cati on AGI
Pros of process-based AGI
It is the simplest form of AGI to implement.
Cons of process-based AGI
It is the least efficient form of AGI with regard to resource consumption. Systems
with high load should consider FastAGI, discussed in FastAGIAGI over
TCP on page 478, instead.
EAGI
EAGI (Enhanced AGI) is a slight variant on AGI(). It is invoked in the Asterisk dialplan
as EAGIQ. The difference is that in addition to the communication on stdin and
stdout, Asterisk also provides a unidirectional stream of audio coming from the channel
on file descriptor 3. For more details on how to invoke EAGI() from the Asterisk dia
lplan, check the documentation built into Asterisk:
*CLI > core showappl i cati on EAGI
AGI Variants | 477
Pros of Enhanced AGI
It has the simplicity of process-based AGI, with the addition of a simple read-only
stream of the channels audio. This is the only variant that offers this feature.
Cons of Enhanced AGI
Since a new process must be spawned to run your application for every cali, it has
the same efficiency concerns as regular process-based AGI.
*- 1 For an alternative way of getting access to the audio outside of
J .
Asterisk, consider using JACK (http://jackaudio.org/). Asterisk has
v a module for JACK integration, called appj ack. It provides the
3ACKQ dialplan application and the 3ACK_H00K( ) dialplan function.
DeadAGI Is Dead
In versions of Asterisk prior to 1.8, there was a dialplan application called DeadAGlQ.
Its purpose was similar to that of AGI (), except you used it on a channel that had already
been hung up. This would usually be done in the special hextensin, when you wanted
to use an AGI application to aid in some type of post-call processing. Invoking Dead
AGI () from the dialplan will still work, but you will get a WARNING message in the Asterisk
log. It has been deprecated in favor of using AGI() in all cases. The code for AGI() has
been updated so it knows how to correctly adjust its operation after a channel has been
hung up.
Pros of DeadAGI
None. Its dead.
Cons of DeadAGI
Its dead. Really, dont use it. If you do, your configuration may break if Dead
AGI() is completely removed from Asterisk in a future versin.
FastAGIAGI over TCP
FastAGI is the term used for AGI cali control over a TCP connection. With process-
based AGI, an instance of an AGI application is executed on the system for every cali
and communication with that application is done over stdin and stdout. With FastAGI,
a TCP connection is made to a FastAGI server. Cali control is done using the same AGI
protocol, but the communication is over the TCP connection and does not require a
new process to be started for every cali. The AGI protocol is discussed in more detail
in AGI Communication Overview on page 480. Using FastAGI is much more scal-
able than process-based AGI, though it is also more complex to implement.
FastAGI is used by invoking the AGI() application in the Asterisk dialplan, but instead
of providing the ame of the application to execute, you provide an a g i :/ / URL. For
example:
ext en => 1234, l , AGI ( agi : / / l 27. 0. 0. l )
478 | Chapter 21: Asterisk Gateway Interface (AGI)
The default port number for a FastAGI connection is 4573. A different port number can
be appended to the URL after a colon. For example:
ext en => l 234, l , AGI ( agi : / / l 27. 0. 0. 1: 4574)
Just as with process-based AGI, arguments can be passed to a FastAGI application. To
do so, add them as additional arguments to the AGI () application, delimited by commas:
ext en => 1234, l , AGI ( agi : / / l 92. 168. 1. 199, argl,aig2,arg3)
FastAGI also supports the usage of SRV records if you provide a URL in the form of
hagi :/ / . By using SRV records, you can list mltiple hosts that Asterisk can attempt to
connect to for purposes of high availability and load balancing. In the following ex
ample, to find a FastAGI server to connect to, Asterisk will do a DNS lookup for
_agi . _t cp. shi f t ei ght . org:
ext en => l 234, l , AGI ( hagi : / / shi f t ei ght . org)
Pros of FastAGI
Its more efficient than process-based AGI. Instead of spawning a process per cali,
a FastAGI server can handle many calis.
DNS can be used to achieve high availability and load balancing among FastAGI
servers to further enhance scalability.
Cons of FastAGI
It is more complex to implement a FastAGI server than to implement a process-
based AGI application. However, implementing a TCP server is something that
has been done countless times before, so there are many examples available for
virtually any programming language.
Async AGIAMKontrolled AGI
Async AGI is a newer method of using AGI that was first introduced in Asterisk 1.6.0.
The purpose of async AGI is to allow an application that uses the Asterisk Manager
Interface (AMI) to asynchronously queue up AGI commands to be executed on a chan-
nel. This can be especially useful if you are already making extensive use of the AMI
and would like to take advantage of the same application to handle cali control, as
opposed to writing a detailed Asterisk dialplan or developing a separate FastAGI server.
*
More information on the Asterisk Manager Interface can be found in
Chapter 20.
'<*
Async AGI is invoked by the AGI() application in the Asterisk dialplan. The argument
to AGI() should be async : agi , as shown in the following example:
ext en => l 234, i , AGI ( async: agi )
AGI Variants | 479
Additional Information on how to use async AGI over the AMI can be found in the next
section.
Pros of async AGI
An existing AMI application can be used to control calis using AGI commands.
Cons of async AGI
It is the most complex method of using AGI to implement.
Setting Up /etc/asterisk/manager.conf for Async AGI
Configurationon page 460 discusses the configuration options in manager.conf in
detail. To make use of async AGI, an AMI account must have the agi permission for
both read and write. For example, the following user defined in manager.conf would
be able to both execute AGI manager actions and receive AGI manager events:
)
; Def i ne a user cal l ed ' hel i o' , wi th a password of worl d' .
; Gi ve thi s user read/ wri te permi ssi ons f or AGI .
[hel i o]
secret =worl d
read =agi
wri te =agi
AGI Communication Overview
The preceding section discussed the variations of AGI that can be used. This section
goes into more detail about how your custom AGI application communicates with
Asterisk once AGI() has been invoked.
Setting Up an AGI Session
Once AGI() or EAGIQ has been invoked from the Asterisk dialplan, some information
is passed to the AGI application to set up the AGI session. This section discusses what
steps are taken at the beginning of an AGI session for the different variants of AGI.
Process-based AGI/FastAGI
For a process-based AGI application or a connection to a FastAGI server, the variables
listed in Table 21-1 will be the first pieces of information sent from Asterisk to your
application. Each variable will be on its own line, in the form:
agi _vari abl e: valu
480 | Chapter 21: Asterisk Gateway Interface (AGI)
Cable21-1. AGI environment variables
Variable Valu/Example Description
agi_request hello-world.sh The first argument that was passed to the AGI () or
EAGI () application. For process-based AGI, this is the ame
of the AGI application that has been executed. For FastAGI, this
would be the URLthat was used to reach the FastAGI server.
agi_channel SIP/
0004F2060EB4-00000009
The ame of the channel that has executed the AGI () or
EAGI () application.
agi_language en The language set on agi_channel.
agijype SIP The channel type for agi_channel.
agi_uniqueid
1284382003.9 The uniqueid of agi_channel.
agi_version l.8.0-beta4 The Asterisk versin in use.
agi_callerid 12565551212 The full caller IDstring that is set on agi_channel.
agi_callerid
ame
Russell Bryant The caller IDame that isset on agi_channel.
agi_callingpres 0 The caller presentation associated with the caller IDset on
agi_c ha nne 1. For more information, seethe output of core
show fundn CALLERPRES at the Asterisk CU.
agi_callingani2 0 The caller ANI2 associated with agi_channel.
agi_callington 0 The caller IDTON(Type of Number) associated with
agi_channel.
agi_callingtns 0 The dialed number TNS(Transit Network Select) associated
with agi_channel.
agi_dnid 7010 The dialed number associated with agi_channel.
agi_rdnis unknown The redirecting number associated with agi_channel.
agi_context phones The context of the dialplan that agi_channel was in when
it executed the AGI () or EAGI () application.
agi_extension 500 The extensin in the dialplan that agi_channel was exe-
cuting when it ran the AGI () or EAGI () application.
agi_priority 1 Thepriorityofagi_extensioninagi_context that exe
cuted AGI ()or EAGI ().
agi_enhanced 0.0 An indication of whether AGI () or EAGI () was used from
the dialplan. 0.0 indicates that AGI () was used. 1.0 indi-
cates that EAGI () was used.
agi_accountcode myaccount The accountcode associated with agi_channel.
agi_threadid 140071216785168 The threadid of the thread in Asterisk that is running the
AGI () or EAGI () application. This may be useful for associ-
ating logsgenerated by the AGI application with logsgenerated
by Asterisk, since the Asterisk logs contain thread IDs.
agi_arg_<argu
ment number>
my argument These variables provide the contents of the additional argu
ments provided to the AGI () or EAGI () application.
AGI Communication Overview | 481
For an example of the variables that might be sent to an AGI application, see the AGI
communication debug output in Quick Start on page 475. The end of the list of
variables will be indicated by a blank line. Example 21-1 handles these variables by
reading Unes of input in a loop until a blank line is received. At that point, the appli
cation contines and begins executing AGI commands.
Async AGI
When you use async AGI, Asterisk will send out a manager event to initiate the async
AGI session. Here is an example manager event sent out by Asterisk:
Event: AsyncAGI
Pri vi l ege: agi , al l
SubEvent: Start
Channel : SI P/ OOOOFFFFOOOl - OOOOOOOO
Env: agi _request %3A%2Oasync%0Aagi _channel %3A%2OSI P%2FOOOOFFFFOOOl - OOO0OOO0%0A \
agi _l anguage%3A%20en%0Aagi _t ype%3A%20SI P%0Aagi _uni quei d%3A%201285219743. 0%0A \
agi _versi 0n%3A%201. 8. 0- bet a5%0Aagi _cal l eri d%3A%2012565551111%0A \
agi _cal l eri dname%3A%203ul i e%20Bryant %0Aagi _cal l i ngpres%3A%200%0A \
agi _cal l i ngani 2%3A%200%0Aagi _cal l i ngt on%3A%200%0Aagi _cal l i ngt ns%3A%200%0A \
agi _dni d%3A%2011l %0Aagi _rdni s%3A%20unknown%0Aagi _cont ext %3A%20Local Set s%0A \
agi _ext ensi on%3A%20l l l %0Aagi _pri ori t y%3A%20l %0Aagi _enhanced%3A%200. 0%0A \
agi _account code%3A%20%0Aagi _t hreadi d%3A%20- l 339524208%0A%0A
j *
*___
- > I The valu of the Env header in this AsyncAGI manager event is all on one
^ line. The long valu of the Env header has been URI encoded.
Commands and Responses
Once an AGI session has been set up, Asterisk begins performing cali processing in
response to commands sent from the AGI application. As soon as an AGI command
has been issued to Asterisk, no further commands will be processed on that channel
until the current command has been completed. When it finishes processing a com
mand, Asterisk will respond with the result.
The AGI processes commands in a serial manner. Once a command has
been executed, no further commands can be executed until Asterisk has
v returned a response. Some commands can take a very long time to ex-
ecute. For example, the EXEC AGI command executes an Asterisk ap
plication. If the command is EXEC Dial, AGI communication is blocked
until the cali is done. If your AGI application needs to interact further
with Asterisk at this point, it can do so using the AMI, which is covered
in Chapter 20.
482 | Chapter 21: Asterisk Gateway Interface (AGI)
A full list of available AGI commands can be retrieved from the Asterisk consol by
running the command agi show commands. These commands are described in Ta-
ble 21-2. To get more detailed information on a specific AGI command, including
syntax information for any arguments that a command expects, use agi show commands
topic <COMMAND>. For example, to see the built-in documentation for the ANSWER
AGI command, you would use agi show commands topic ANSWER.
Table 21-2. AGI commands
AGI command
ANSWER
ASVNCAGI BREAK
CHANNELSTATUS
DATABASE DEL
DATABASE DELTREE
DATABASE GET
DATABASE PUT
EXEC
GET DATA
GET FULLVARIABLE
GET OPTION
GET VARIABLE
HANGUP
NOOP
RECEIVE CHAR
RECEIVE TEXT
RECORD FILE
SAY ALPHA
Description
Answer the ncoming cali.
Endan async AGI session and have the channel return to the Asterisk dialplan.
Retrieve the status of the channel. This is used to retrieve the current State of the channel, such as
up (answered), down (hung up), or ringing.
Delete akey/value pairfrom the built-in AstDB.
Delete atree of key/value pairs fromthe built-in AstDB.
Retrieve the valu for akey in the AstDB.
Set the valu for akey in the AstDB.
Execute an Asterisk dialplan application on the channel. This command is very powerful in that
between EXECand GET FULL VARIABLE, you can do anything with the cali that you can do
fromthe Asterisk dialplan.
Readdigits fromthe caller.
Evaluatean Asteriskdialplanexpression. Youcansendastringthatcontainsvariablesand/ordialplan
functions, and Asterisk will return the result after making the appropriate substitutions. This com
mand is very powerful in that between EXECand GET FULL VARIABLE, you can do anything
with the cali that you can do from the Asterisk dialplan.
Streamasound file while waiting for adigit fromthe caller. This issimilar to the Back
ground() dialplan application.
Retrieve the valu of achannel variable.
Hang up the channel.3
Donothing. You will get aresult response fromthis command, just like any other. It can be used as
asimple test of the communication path with Asterisk.
Receive asingle character. This only works for channel types that support it, such asIAX2 using
TEXT framesor SIPusing theMESSAGE method.
Receive atext message. This only works in the same cases asRECEIVE CHAR.
Record the audio fromthe caller to afile. This is ablocking operation similar to the Record ()
dialplan application. Torecord acali in the background while you performother operations, use
EXECMonitororEXEC MixMonitor.
Say astring of characters. You can find an example of this in"Quick Start" on page 475. Toget
localized handling of this and the other SAYcommands, set the channel language either in the
device configuration file (e.g., sip.conf) or in the dialplan, by setting the CHANNEL(language)
dialplan function.
AGI Communication Overview | 483
AGI command
SAY DIGITS
SAY NUMBER
SAY PHONETIC
SAY DATE
SAY TIME
SAY DATETIME
SEND IMAGE
SEND TEXT
SET AUTOHANGUP
SET CALLERID
SET CONTEXT
SET EXTENSION
SET MUSIC
SET PRIORITY
SET VARIABLE
STREAM FILE
CONTROL STREAM
FILE
TDD MODE
VERBOSE
WAIT FOR DIGIT
SPEECH CREATE
SPEECH SET
SPEECH DESTROY
SPEECHLOAD
GRAMMAR
SPEECH UNLOAD
GRAMMAR
SPEECHACTIVATE
GRAMMAR
Description
Say astring of digits. For example, 100 would be said as "one zero zero" if the channel's language
is set to Gnglish.
Say anumber. For example, 100 would be said as"one hundred" if the channel's language is set to
English.
Say astring of characters, but useacommon word for each letter (Alpha, Bravo, Charlie...).
Say agiven date.
Sayagiven time.
Say agiven date and time using aspecified format.
Send an image to achannel. IAX2 supports this, but there are no actively developed IAX2 dients
that support it that we know of.
Send text to achannel that supports it. This can be used with SIPand IAX2 channels, at least.
Schedule the channel to be hung up at aspecified point in time in the future.
Set the caller IDame and number on the channel.
Set the current dialplan context on the channel.
Set the current dialplan extensin on the channel.
Start or stop music on hold on the channel.
Set the current dialplan priority on the channel.
Set achannel variable to agiven valu.
Streamthe contents of afile to achannel.
Streamthe contents of afile to achannel, but also allow the channel to control the stream. For
example, the channel can pause, rewind, or fast forward the stream.
Toggle the TDD(Telecommunications Device for the Deaf) mode on the channel.
Send amessage to the verbose logger channel. Verbose messages show up on the Asterisk consol
if the verbose setting is set high enough. Verbose messages will also go to any log file that has been
configured for the verbose logger channel in /etc/asterisk/logger.conf.
Wait for the caller to press adigit.
Initialize speech recognition. This must be done before using other speech AGI commands.b
Set aspeech engine setting. The settings that are available are specific to the speech recognition
engine in use.
Destroy resources that were allocated for doing speech recognition. This command should be the
last speech command executed.
Load agrammar.
Unload agrammar.
Actvate agrammar that has been loaded.
484 | Chapter 21: Asterisk Gateway Interface (AGI)
Description
Deactivateagrammar.
Play aprompt and performspeech recognition, aswell as wait for digits to be pressed.
Execute adialplan subroutine. This will performin the same way as the GoSub() dialplan appli
cation.
a When the HANGUPAGI command isused, the channel isnot immediately hung up. Instead, the channel ismarked asneeding to behung
up. Your AGI application must exit first before Asterisk will continu and performthe actual hangup process.
b While Asterisk includes acore API for handling speechrecognition, it does not come with amodule that provides aspeechrecognition
engine. Digiumcurrently provides two commercial options for speech recognition: Lumenvox (http://www.digium.com/en/products/
software/lumenvox.php) and Vestec (http://www.digium.com/en/products/software/vestec.php).
AGI command
SPEECHDEACTIVATE
GRAMMAR
SPEECHRECOGNIZE
GOSUB
Process-based AGI/FastAGI
AGI commands are sent to Asterisk on a single line. The line must end with a single
newline character. Once a command has been sent to Asterisk, no further commands
will be processed until the last command has finished and a response has been sent
back to the AGI application. Here is an example response to an AGI command:
200 r esul t o
* *
V r -
>? A*
The Asterisk consol allows debugging the Communications with an
AGI application. To enable AGI communication debugging, run the agi
set debug on command. To turn debugging off, use agi set debug off.
While this debugging mode is on, all communication to and from an
AGI application will be printed out to the Asterisk consol. An example
of this output can be found in Quick Starton page 475.
Async AGI
When youre using async AGI, commands are issued by using the AGI manager action.
To see the built-in documentation for the AGI manager action, run manager show
command AGI at the Asterisk CLI. A demonstration will help clarify how AGI com
mands are executed using the async AGI method. First, an extensin is created in the
dialplan that runs an async AGI session on a channel:
ext en => 7011, l , AGI ( agi : async)
The following shows an example manager action execution and the manager events
that are emitted during async AGI processing. After the initial execution of the AGI
manager action, there is an immediate response to indicate that the command has been
queued up for execution. Later, there is a manager event that indicates that the queued
command has been executed. The CommandI Dheader can be used to associate the initial
request with the event that indicates that the command has been executed:
Acti on: AGI
Channel : SI P/ 0004F2060EB4-00000013
Acti onI D: my-acti on-i d
AGI Communication Overview | 485
Commandl D: my- command- i d
Command: VERBOSE "Puppi es l i ke cotton candy. " 1
Response: Success
Act i onl O: my- act i on- i d
Message: Added AGI command to queue
Event: AsyncAGI
Pri vi l ege: agi , al l
SubEvent: Exec
Channel : SI P/ 0004F2060EB4- 00000013
Commandl D: my- command- i d
Resul t: 200%20resul t %3Dl %0A
The following output is what was seen on the Asterisk consol during this async AGI
session:
-- Execut i ng [ 7011@phones: l ] AGI ( "SI P/ 0004F2060EB4- 00000013",
"agi : async") i n new stack
agi : async: Puppi es l i ke cot t on candy.
== Spawn ext ensi n (phones, 7011, 1) exi t ed non- zero on ' SI P/ 0004F2060EB4- 00000013'
Ending an AG Session
An AGI session ends when your AGI application is ready for it to end. The details about
how this happens depend on whether your application is using process-based AGI,
FastAGI, or async AGI.
Process-based AGI/FastAGI
Your AGI application may exit or cise its connection at any time. As long as the channel
has not hung up before your application ends, dialplan execution will continu. If
channel hangup occurs while your AGI session is still active, Asterisk will provide no-
tification that this has occurred so that your application can adjust its operation as
appropriate.
This is an area where behavior has changed since Asterisk 1.4. In
Asterisk 1.4 and earlier versions, AGI would automatically exit and stop
operation as soon as the channel hung up. It now gives your application
the opportunity to continu running if needed.
If a channel hangs up while your AGI application is still executing, a couple of things
will happen. If an AGI command is in the middle of executing, you may receive a result
code of -l . You should not depend on this, though, since not all AGI commands require
channel interaction. If the command being executed does not require channel interac-
tion, the result will not reflect the hangup.
The next thing that happens after a channel hangs up is that an explicit notification of
the hangup is sent to your application. For process-based AGI, the signal SIGHUP will
486 | Chapter 21: Asterisk Gateway Interface (AGI)
be sent to the process to notify it of the hangup. For a FastAGI connection, Asterisk
will send a line containing the word HANGUP. If you would like to disable having Asterisk
send the SI GHUP signal to your process-based AGI application or the HANGUP string to
your FastAGI server, you can do so by setting the AGI SI GHUP channel variable, as dem-
onstrated in the following short example:
)
; Don' t send SI GHUP to an AGI process
; or t he "HANGUP" stri ng to a FastAGI server.
xt en => 500, 1, Set ( AGI SI GHUP=no)
same => n, AGI ( my- agi - appl i cat i on)
At this point, Asterisk automatically adjusts its operation to be in DeadAGI mode. This
just means that an AGI application can run on a channel that has been hung up. The
only AGI commands that may be used at this point are those that do not require channel
interaction. The documentation for the AGI commands built into Asterisk includes an
indication of whether or not each command can be used once the channel has been
hung up.
Async AGI
When youre using async AGI, the manager interface provides mechanisms to notify
you about channel hangups. When you would like to end an async AGI session for a
channel, you must execute the ASYNCAGI BREAK command. When the async AGI session
ends, Asterisk will send an AsyncAGI manager event with a SubEvent of End. The fol
lowing is an example of ending an async AGI session:
Acti on: AGI
Channel : SI P/ 0004F2060EB4-000000l b
Acti onI D: my-acti on-i d
CommandI D: my-command-i d
Command: ASYNCAGI BREAK
Response: Success
Act i onI D: my- act i on- i d
Message: Added AGI command to queue
Event: AsyncAGI
Pri vi l ege: agi , al l
SubEvent: End
Channel : SI P/ 0004F2060EB4- 000000l b
At this point, the channel returns to the Asterisk dialplan if it has not yet been hung up.
Development Frameworks
There have been a number of efforts to create frameworks or libraries that make AGI
programming easier. Table 21-3 lists some of them. If you do not see a library listed
here for your preferred programming language, do a quick search for it and youre likely
to find one, as others do exist.
Development Frameworks | 487
Table21-3. AGI development frameworks
Framework Language URL
Adhearsion Ruby http-J/adhearsion.com/
StarPy Python http://starpy.sourceforge.net/
Asterisk-Java Java http://asterisk-java.org/
Asterisk-perl Perl http-J/asterisk.gnuinter.net/
PHPAGI PHP http://phpagi.sourceforge.net/
Conclusin
AGI provides a powerful interface to Asterisk that allows you to implement first-party
cali control in the programming language of your choice. There are mltiple approaches
that you can take to implementing an AGI application. Some approaches can provide
better performance, but at the cost of more complexity. AGI provides a programming
environment that may make it easier to integrate Asterisk with other systems, or just
provide a more comfortable cali control programming environment for the experienced
programmer.
__________________________________CHAPTER 20
Asterisk Manager Interface (AMI)
John Malkovich: I have seen a world that
NO man should see!
Craig Schwartz: Really? Becausefor most people its a
rather enjoyable experience.
Beingjohn Malkovich
The Asterisk Manager Interface (AMI) is a system monitoring and management inter
face provided by Asterisk. It allows live monitoring of events that occur in the system,
as well enabling you to request that Asterisk perform some action. The actions that are
available are wide-ranging and include things such as returning status information and
originating new calis. Many interesting applications have been developed on top of
Asterisk that take advantage of the AMI as their primary interface to Asterisk.
Quick Start
This section is for getting your hands dirty with the AMI as quickly as possible. First,
put the following configuration in etc/asterisk/manager.conf:
; Turn on the AMI and ask i t to onl y accept connect i ons f roml ocal host.
[general ]
enabl ed =yes
webenabl ed =yes
bi ndaddr = 127. O. O.1
; Creat e an account cal l ed "hel i o", wi t h a password of "worl d"
[hel i o]
secret =worl d
457
*+%
* I This sample configuration is set up to only allow local connections to
theAMI. Ifyouintendon making this interface available overa network,
ti-?,1it is strongly recommended that you only do so using TLS. The use of
TLS is discussed in more detail later in this chapter.
Once the AM1 configuration is ready, enable the built-in HTTP server by putting the
following contents in /etc/asterisk/http.conf:
y
;Enabl e the bui l t - i n HTTP server, and onl y l i sten f or connect i ons on l ocal host.
[general ]
enabl ed =yes
bi ndaddr =127. O. O.1
AMI over TCP
There are mltiple ways to connect to the AMI, but a TCP socket is the most common.
We will use telnet to demnstrate AMI connectivity. This example shows these steps:
1. Connect to the AMI over a TCP socket on port 5038.
2. Log in using the Logi n action.
3. Execute the Pi ng action.
4. Log off using the Logof f action.
Heres how the AMI responds to those actions:
$ tel net l ocal host 5038
Tryi ng 127. O. O. 1...
Connect ed to l ocal host.
Escape charact er i s
Ast eri sk Cal i Manager/ l . l
Acti on: Logi n
Userame: hel i o
Secret: worl d
Response: Success
Message: Aut hent i cat i on accept ed
Acti on: Pi ng
Response: Success
Pi ng: Pong
Ti mestamp: 1282739190. 454046
Acti on: Logoff
Response: Goodbye
Message: Thanks f or al l the f i sh.
Connect i on cl osed by f orei gn host.
458 | Chapter 20: Asterisk Manager Interface (AMI)
Once you have this working, you have verified that AMI is accepting connections via
a TCP connection.
AMI over HTTP
It is also possible to use the AMI over HTTP. In this section we will perform the same
actions as before, but over HTTP instead of the native TCP interface to the AMI. The
responses will be delivered over HTTP in the same format as the previous example,
since the rawman encoding type is being used. AMI-over-HTTP responses can be enco-
ded in other formats, such as XML. These response-formatting options are covered in
AMI over HTTP on page 467.
r*
____ I
Accounts used for connecting to the AMI over HTTP are the same ac-
counts configured in /etc/asterisk/manager.conf.
This example demonstrates how to access the AMI over HTTP, log in, execute the
Pi ng action, and log off:
$ wget "http:/ / l ocal host: 8088/ rawman?acti on=l ogi n&username=hel l o&secret=worl d" \
>--save-cooki es cooki es. txt -0 -
- - 2010- 08- 31 12: 34: 23- -
Resol vi ng l ocal host. . . 127. 0. 0. 1
Connect i ng to l ocal host | 127. 0. 0. l | : 8088. .. connected.
HTTP request sent, awai t i ng response. . . 200 0K
Length: 55 [ t ext/ pl ai n]
Savi ng to: ' STDOUT'
Response: Success
Message: Aut hent i cat i on accept ed
2010- 08- 31 12: 34: 23 (662 KB/ s) - wri t t en to stdout [55/ 55]
$ wget "http: / / l ocal host: 8088/ rawman?acti on=pi ng" --l oad-cooki es cooki es. txt -0 -
- - 2010- 08- 31 12: 34: 23- -
Resol vi ng l ocal host. . . 127. 0. 0. 1
Connect i ng to l ocal host | l 27. 0. 0. l | : 8088. . . connected.
HTTP request sent, awai t i ng response. . . 200 0K
Length: 63 [text/ pl ai n]
Savi ng to: ' STDOUT'
Response: Success
Pi ng: Pong
Ti mestamp: 1283258063. 040293
2010- 08- 31 12: 34: 23 (775 KB/ s) - wri t t en to stdout [63/ 63]
Quick Start | 459
$ wget "http: / / l ocal host: 8088/ rawman?acti on=l ogoff" l oad-cooki es cooki es. txt -0 -
- - 2010- 08- 31 12: 34: 23- -
Resol vi ng l ocal host. . . 127. 0. 0. 1
Connect i ng to l ocal host | 127. 0. 0. l | : 8088. . . connected.
HTTP request sent, awai t i ng response. . . 200 OK
Length: 56 [text/ pl ai n]
Savi ng to: ' STDOUT'
Response: Goodbye
Message: Thanks f or al l t he f i sh.
2010- 08- 31 12: 34: 23 (696 KB/ s) - wri t t en to stdout [56/ 56]
The HTTP interface to AMI lets you integrate Asterisk cali control into a web Service.
Configuration
The section Quick Start on page 457 showed a very basic set of configuration files to
get you started. However, there are many more options available for the AMI.
manager.conf
The main configuration file for the AMI is /etc/asterisk/manager.conf. The [general ]
section contains options (listed in Table 20-1) that control the overall operation of the
AMI. Any other sections in the manager.conf file will define accounts for logging in and
using the AMI.
Table 20-1. Options in the manager.conf [general] section
Option Value/Example Description
enabled yes Enables the AMI. The default isno.
webenabled yes Allows access to the AMI through the built-in HTTP
server. The default is no.a
port 5038 Sets the port number to listen on for AMI connections.
The default is 5038.
bindaddr 127. 0. 0. 1 Sets the address to listen on for AMI connections. The
default is to listen on all addresses (0. 0. 0. 0). How
ever, it ishighly recommended to set this to
127. O. O. 1.
tlsenable yes Enables listening for AMI connections using TLS. The
default is no. It ishighly recommended to only expose
connectivity via TLSoutside of the local machine.b
tlsbindport 5039 Sets the port to listen on for TLSconnections to the
AMI. The default is 5039.
460 | Chapter 20: Asterisk Manager Interface (AMI)
Option
t l sbi ndaddr
t l scert f i l e
t l spri vat ekey
t l sci pher
Value/Example
O . O . 0 . 0
/var/lib/astersk/keys/astersk.pem
/m/lib/asterisk/keys/private.pem
<ci pher st ri ng>
al l owmul t i pl el ogi n no
di spl ayconnect s yes
t i mest ampevent s no
brokenevent sact i on no
channel vars
debug
ht t pt i meout
VAR1JVAR2, VAR3[ , VAR4[ . . . ] ]
no
60
Description
Sets the address to listen on for TLS-based AMI con
nections. The default is to listen on all addresses
(o.o.o.o).
Sets the path to the server certifcate for TLS. This is
required if tlsenable is set to yes.
Sets the path to the prvate key for TLS. If this is not
specifted, the t l s c e r t f i l e will be checked to see
if it also contains the prvate key.
Specifies alst of ciphers for OpenSSL to use. Setting
this is optonal. Toseealist of available ciphers, run
openssl ciphers -vat the command line.
Allows the same account to make more than one con-
nection at the same time. The default is yes.
Reports connections to the AMI as verbose messages
printed to the Asterisk consol. This isusually useful,
but it can get in the way on asystemthat uses scripts
that make alot of connections to the AMI. The default
is yes.
Adds aUnix epoch-based timestamp to every event
reported to the AMI. The default is no.
Restores previously broken behavior for the Events
AMI action, where aresponse would not be sent in
some circumstances. This option is there for the sake
of backward-compatibil ity for applications that
worked around abug and should not be used unless
absolutely necessary. The default is no.
Specifies alist of channel variables to inciude with all
manager events that are channel-oriented. The de
fault is to inciude no channel variables.
Enables some additional debugging in the AMI code.
This isprimarily there for developers of the Asterisk C
code. The default is no.
Sets the HTTPtimeout, in seconds. This timeout affects
users of the AMI over HTTP: it sets the Ma x - Age of the
HTTPcookie, sets how long events are cached to allow
retrieval of the events over HTTPusing the WaitE
vent s action, and the amount of time that the HTTP
server keeps asession alive after completing an AMI
action. The default is 60 seconds.
a Toaccessthe AMI over HTTP, the built-in HTTPserver must also beconfigured in /etc/asterisk/http.conf.
b TheOpenSSLdevelopment package must beinstalled for Asterisk to be able to useencryption. OnUbuntu, the package islibssl-dev. On
CentOS, the package isopenssl-devel.
Configuration | 461
The manager.conf configuration file also contains the configuration of AMI user ac-
counts. An account is created by adding a section with the username inside square
brackets. Within each [username] section there are options that can be set that will
apply only to that account. Table 20-2 lists the options available in a [username] section.
Table 20-2. Options for [username] sections
Option Value/Example
secret password
deny 0.0.0.0/0.0.0.0
permit 192.168.1.0/255.255.255.0
writetimeout 100
displayconnects yes
read system,cali[ , . . . ]
write system,cali[ , . . . ]
eventfilter IChannel: DAHDI*
Description
Sets the password used for authentication. This must be set.
Sets an IPaddress Access Control List (ACL) for addresses that
should be denied the ability to authenticate asthis user. By
default this option isnotset.
Sets an IPaddress ACLfor addresses that should be allowed
to authenticate as this user. As with deny, by default this
option is not set. Without these options set, any IPaddress
that can reach the AMI will be allowed to authenticate as
this user.
Sets the timeout used by Asterisk when writing data to the
AMI connection for this user. This option is specified in mil-
liseconds. The default valu is 100.
Also available in the [general] section (refer to
Table 20-1), but can be controlled on aper-user basis.
Defines which manager events this user will receive. By de
fault, the user will receive no events. Table 20-3 covers the
availablepermissiontypesforthereadandwriteoptions.
Defines which manager actions this user is allowed to exe-
cute. By default, the user will not be able to execute any
actions. Table 20-3 covers the available permission types for
the read and write options.
Used to provide awhitelist- or blacklist-style filtering of
manager events before they are delivered to the AMI dient
application. Filters are specified using aregular expression.
Aspecified filter is awhitelist filter unless preceded by an
exdamation point.3
a If no filters are specified, all events that are allowed basedon the read option will be delivered. If only whitelist filters have been specified,
only events that match one of the filters will be delivered. If there are only blacklist-style filters, all events that do not match any of the
filters will be delivered. Finally, if there isa mix of whitelist- and blacklist-style filters, the whitelist filters will be processedfirst, and then
the blacklist filters.
As discussed in Table 20-2, the read and wri t e options set which manager actions and
manager events a particular user has access to. Table 20-3 shows the available permis
sion vales that can be specified for these options.
462 | Chapter 20: Asterisk Manager Interface (AMI)
Table 20-3. Availablevales for AMI user account read/writeoptions
Permission identifier read write
a l l Shorthand way of specifying that this user
should have access to all available privilege
options.
Grants user all privilege options.
system Allows user to receive general systemInfor
mation, such as notifications of configuration
reloads.
Allows user to performsystemmanagement com
mands such as Restan, Reload, or Shutdown.
c a li Allows user to receive events about channels
on the system.
Allows userto set information on channels.
log Gives user access to logging information.3 read-only
verbose Gives user access to verbose logging
information.b
read-only
agent Gives user access to events regarding the status
of agents fromthe app_queue and
chan_agent modules.
Enables user to performactions for managing and
retrieving the status of queues and agents.
user Grants access to user-defined events, aswell
as events about Jabber/XMPPusers.
Lets user performthe UserEvent manager
action, which provides the ability to request that
Asterisk generate auser-defined event.c
config write-only Allows user to retrieve, update, and reload config
uration files.
command write-only Allows user to execute Asterisk CLI commands over
the AMI.
dtmf Allows user to receive events generated as
DTMFpasses through the Asterisk core.d
read-only
reporting Gives user access to call-quality events, such
asjitterbuffer statistics or RTCPreports.
Enables userto execute arange of actions to retrieve
statistics and status information from across the
system.
cdr Grants user access to CDRrecords reported by
the cdr_manager module.
read-only
dialplan Allows user to receive events generated when
variablesareSetornewextensionsarecreated.
read-only
orignate write-only Allows user to execute the Originate action,
which allows an AMI dient to request that Asterisk
createanewcall.
ag
Allows user to receive events generated when
AGI commands are processed.
Enables userto performactions for managing chan
nels that are running AGI in itsasynchronous mode.
AGI is discussed in more detail in Chapter 21.
cc Allows user to receive events related to Cali
Completion Supplementary Services (CCSS).
read-only
Configuration | 463
Permission identifier read
aoc Lets user seeAdvce of Charge events gener- Allows user to execute the AOCMessage manager
ated as AOCevents are received. action, for sending out AOCmessages.
a This level has been defined, but it is not currently usedanywhere id Asterisk.
b This level has been defined, but it isnot currently usedanywhere in Asterisk.
c TheUser Event action is auseful mechanismfor having messages delivered to other AMI dients.
d OTMFevents will not begenerated in abridged cali between two channels unless generic bridging in the Asterisk core isbeing used. For
example, if the OTMFisbeing transmitted with the media streamand the media streamisflowing directly between the two endpoints,
Asterisk will not beable to report the DTMFevents.
http.conf
As weve seen, the Asterisk Manager Interface can be accessed over HTTP as well as
TCP. To make that work, a very simple HTTP server is embedded in Asterisk. All of
the options relevant to the AMI go in the [general ] section of /etc/asterisk/http.conf.
Enabling access to the AMI over HTTP requires both /etc/asterisk/man-
ager.conf and /etc/asterisk/http.conf. The AMI must be enabled in man
ager.conf, with the enabled option set to yes, and the manager.conf op
tion webenabled must be set to yes to allow access over HTTP. Finally,
the enabled option in http.conf must be set to yes to turn on the HTTP
server itself.
The available options are Usted in Table 20-4:
Table 20-4. Options in the http.conf [general] section
Option Vaiue/Example Description
enabled yes Enables the built-in HTTPserver. The default is no.
bindport 8088 Sets the port number to listen on for HTTPconnections. The default is8088.
bindaddr 127.0. 0.1 Sets the address to listen on for HTTPconnections. The default is to listen on all
addresses (0. o. o. 0). However, it is highly recommended to set this to
127. 0. 0. 1.
tlsenable yes Enables listening for HTTPSconnections. The default isno. It is highly recom
mended that you only use HTTPSif you wish to expose HTTPconnectivity outside
ofthe local machine.3
tlsbindport 8089 Sets the port to listen on for HTTPSconnections. The default is 8089.
tlsbindaddr 0. o. 0.0 Sets the address to listen on for TLS-enabled AMI connections. The default is to
listen on all addresses (o. o. o. o).
t l s c e r t f i l e /var/lib/asterisk/ Sets the path to the HTTPSserver certifcate. This is reguired if tlsenable is set
keys/asterisk.pem toyes.
t lsprivate / var/lib/asterisk/ Sets the path to the HTTPSprvate key. If this is not specified, the tl scert
key keys/private.pem f i l e will be checked to seeif it also contains the prvate key.
464 | Chapter 20: Asterisk Manager Interface (AMI)
Option Value/Example Description
t l sci pher <cipher Specifies alist of ciphers for OpenSSLto use. Setting this is optional. To seealist
string> of available ciphers, run openssl ciphers-vat the command line.
a TheOpenSSLdevelopment package must be installed for Asterisk to be able to useencryption. OnUbuntu, the package islibssl-dev. On
CentOS, the package is openssl-devel.
Protocol Overview
There are two main types of messages on the Asterisk Manager Interface: manager
events and manager actions.
Manager events are one-way messages sent from Asterisk to AMI clients to report
something that has occurred on the system. See Figure 20-1 for a graphical represen-
tation of the transmission of manager events.
AMI Client Asterisk
Manager Event
V
/
Manager Event
N
Manager Event
\
Figure 20-1. Manager events
Manager actions are requests from a client that have associated responses that come
back from Asterisk. That is, a manager action may be a request that Asterisk perform
some action and return the result. For example, there is an AMI action to originate a
new cali. See Figure 20-2 for a graphical representation of a client sending manager
actions and receiving responses.
Other manager actions are requests for data that Asterisk knows about. For example,
there is a manager action to get a list of all active channels on the system: the details
about each channel are delivered as a manager event. When the list of results is com
plete, a final message will be sent to indicate that the end has been reached. See Fig
ure 20-3 for a graphical representation of a client sending this type of manager action
and receiving a list of responses.
Protocol Overview | 465
AMI Client Asterisk j
..................i ...'' ' '' ''...... '
i
Manager Action ^
. ""............ s
i
i
i
Action Response
: <
i
i
! Manager Action ^
; y

t
^ Action Response
i
Figure20-2. Manager actions
AMI Client | Asterisk
i
i
i
i
i
:
Manager Event
>
1
1
1
1
Manager Event
i
*
i
1
'
Manager Event
' S

i
i
i
Action Response
Figure20-3. Manager actions that return a list of data
Message Encoding
All AMI messages, including manager events, manager actions, and manager action
responses, are encoded in the same way. The messages are text-based, with lines ter-
minated by a carriage return and a line-feed character. A message is terminated by a
blank line:
Headerl : Thi s i s the f i rst header<CR><LF>
Header2: Thi s i s the second header<CR><LF>
Header3: Thi s i s t he l ast header of thi s message<CR><LF>
<CRxLF>
466 | Chapter 20: Asterisk Manager Interface (AMI)
Events
Manager events always have an Event header and a Pri vi l ege header. The Event header
gives the ame of the event, while the Pri vi l ege header lists the privilege levels asso-
ciated with the event. Any other headers included with the event are specific to the
event type. Heres an example:
Event: Hangup
Pri vi l ege: cal i , al l
Channel : SI P/ 0004F2060EB4- 00000000
Uni quei d: 1283174108. 0
Cal l erI DNum: 2565551212
Cal l erl DName: Russel l Bryant
Cause: 16
Cause- t xt : Normal Cl eari ng
Actions
When executing a manager action, it must include the Action header. The Action header
identifies which manager action is being executed. The rest of the headers are argu-
ments to the manager action. Some headers are required.
m\
I To get a list of the headers associated with a particular manager action,
type manager show command <Action> at the Asterisk command line.
" il-y To get a full list of manager actions supported by the versin of Asterisk
you are running, enter manager show commands at the Asterisk CLI.
The final response to a manager action is typically a message that includes the
Response header. The valu of the Response header will be Success if the manager action
was successfully executed. If the manager action was not successfully executed, the
valu of the Response header will be Error. For example:
Acti on: Logi n
Username: russel l
Secret: russel l
Response: Success
Message: Aut hent i cat i on accept ed
AMI over HTTP
In addition to the native TCP interface, it is also possible to access the Asterisk Manager
Interface over HTTP. Programmers with previous experience writing applications that
use web APIs will likely prefer this over the native TCP connectivity.
Authentication and session handling
There are two methods of performing authentication against the AMI over HTTP. The
first is to use the Login action, similar to authentication with the native TCP interface.
Protocol Overview | 467
This is the method that was used in the quick-start example, as seen in AMI over
HTTP on page 459. The second authentication option is HTTP digest authentica-
tion.* The next three sections discuss each of the AMI over HTTP encoding options.
To indicate that HTTP digest authentication should be used, prefix the encoding type
with an a.
Once successfully authenticated, Asterisk will provide a cookie that identifies the au-
thenticated session. Here is an example response to the Logi n action that includes a
session cookie from Asterisk:
$ curl -v "http: / / l ocal host: 8088/ rawman?acti on=l ogi n&username=hel l o&secret=worl d"
* About t o connect () t o l ocal host port 8088 (#0)
* Tryi ng 127. 0. 0. 1. . . connect ed
* Connect ed t o l ocal host (127. 0. 0. 1) port 8088 (#0)
>GET / rawman ?act i on=l ogi n&username=hel l o8i secret=wor I da HTTP/ l . l
>User- Agent : curl / 7. 19. 7 ( x86_64- pc- l i nux- gnu) l i bcurl / 7. 19. 7
OpenSSL/ 0. 9. 8k zl i b/ l . 2. 3. 3 l i bi dn/ 1.15
>Host: l ocal host : 8088
>Accept: */ *
>
<HTTP/ l . l 200 0K
<Server: Ast eri sk/ l . 8. 0- bet a4
<Date: Tue, 07 Sep 2010 11: 51: 28 GMT
<Connecti on: ci se
<Cache- Cont rol : no- cache, no- st ore
<Cont ent - Lengt h: 55
<Cont ent - t ype: t ext / pl ai n
<Cache- Cont rol : no- cache;
<Set - Cooki e: mansessi on_i d=' ' 0e929e60"; Versi on=l ; Max- Age=60
<Pragma: SuppressEvent s
Response: Success
Message: Aut hent i cat i on accept ed
* Cl osi ng connect i on #0
/rawman encoding
The rawman encoding type is what has been used in all the AMI over HTTP examples
in this chapter so far. The responses received from requests using rawman are formatted
in the exact same way that they would be if the requests were sent over a direct TCP
connection to the AMI.
* At the time of writing, there is a problem with HTTP digest authentication that prevents it from working
properly. Issue 18598 (https://issuesMsterisk.org/view.php?id=18598) in the Asterisk project issue tracker has
been opened for this problem. Hopefully it will be fixed by the time you read this.
468 | Chapter 20: Asterisk Manager Interface (AMI)
/manager encoding
The manager encoding type provides a response in simple HTML form. This interface
is primarily useful for experimenting with the AMI. Here is an example Logi n using this
encoding type:
$ curl -v ,,http: / / l ocal host: 8088/ manager?acti on=l ogi n&username=hel l o&secret=worl d"
* About to connect Q to l ocal host port 8088 (#0)
* Tryi ng 127. O. O. 1. . . connect ed
* Connect ed to l ocal host (127. 0. 0. 1) port 8088 (#0)
>GET / manager?act i on=l ogi n&username=hel l o&secret =worl d HTTP/ 1.1
>User- Agent : curl / 7. 19. 7 ( x86_64- pc- l i nux- gnu) l i bcur1/ 7. 19. 7
0penSSL/ 0. 9. 8k zl i b/ l . 2. 3.3 l i bi dn/ l . 15
>Host: l ocal host : 8088
>Accept: */ *
>
<HTTP/ 1. 1 200 OK
<Server: Ast eri sk/ l . 8. 0- bet a4
<Date: Tue, 07 Sep 2010 12: 19: 05 GMT
<Connecti on: ci se
<Cache- Cont rol : no- cache, no- store
<Content - Lengt h: 881
<Cont ent - t ype: text / ht ml
<Cache- Cont rol : no- cache;
<Set- Cooki e: mansessi on_i d="l 39deda7"; Versi on=l ; Max- Age=60
<Pragma: SuppressEvent s
<t i t l e>Ast eri sk&t rade; Manager I nt er f acec/ t i t l exbody bgcol or="#f f f f f f ">
<tabl e al i gn=cent er bgcol or="#f l f l f l " wi dt h="500">
ct r xt d col span="2" bgcol or="#f l f l f f "xhl >Manager Test er </ hi x/ t dx/ t r >
<t r xt d col span="2" bgcol or=,' #f i f l f f "xf or macti on=' ' manager" met hod="post ">
Acti on: <sel ect name="act i on">
<opti on val ue="">. . . . &gt ; </ opt i on>
<opti on val ue="l ogi n">l ogi n</ opt i on>
<opti on val ue="command>Command</ opt i on>
copti on val ue="wai t event >wai t event </ opt i on>
<opti on val ue="l i st commands">l i st commands</ opt i on>
</ sel ect>
or ci nput name="act i on"xbr / >
CLI Command <i nput name="command"xbr >
user <i nput name="username"> pass ci nput t ype="password" name="secr et "xbr >
<i nput type="submi t ">
</ f orm>
</ t dx/ t r >
<t r xt d>Response</ t dxt d>Success</ t dx/ t r >
<t r xt d>Message</ t dxt d>Aut hent i cat i on accept ed</ t dx/ t r >
<t r xt d col span=,,2' ,xhr x/ t dx/ t r >
* Cl osi ng connecti on #0
</ t abl ex/ body
Protocol Overview | 469
The mxml encoding type provides responses to manager actions encoded in XML. Here
is an example Logi n using the mxml encoding type:
$ curl - v "ht t p: / / l ocal host : 8088/ mxml ?act i on=l ogi n&username=hel l o&secret =worl d"
* About to connect Q t o l ocal host port 8088 (#0)
* Tryi ng 127. 0. 0. 1. . . connect ed
* Connect ed t o l ocal host ( 127. 0. 0. 1) port 8088 (#0)
>GET / mxml ?act i on=l ogi n&username=hel l o&secret =worl d HTTP/ l . l
>User- Agent: curl / 7. 19. 7 ( x86_64- pc- l i nux- gnu) l i bcurl / 7. 19- 7
0penSSL/ O. 9. 8k zl i b/ l . 2. 3. 3 l i bi dn/ l . 15
>Host: l ocal host : 8088
>Accept: */ *
>
<HTTP/ l . l 200 0K
<Server: Ast eri sk/ l . 8. 0- bet a4
<Date: Tue, 07 Sep 2010 12: 26: 58 GMT
<Connecti on: ci se
<Cache- Cont rol : no- cache, no- st ore
<Cont ent - Lengt h: 146
<Cont ent - t ype: t ext / xml
<Cache- Cont rol : no- cache;
<Set- Cooki e: mansessi on_i d="536dl 7a4"; Versi on=l ; Max- Age=60
<Pragma: SuppressEvent s
<
<aj ax- response>
<response type=' obj ect ' i d=' unknown' >
<generi c response=' Success' message=' Aut hent i cat i on accepted' / >
</ response>
* Cl osi ng connect i on #0
</ aj ax- response>
Manager events
When connected to the native TCP interface for the AMI, manager events are delivered
asynchronously. When using the AMI over HTTP, events must be retrieved by polling
for them. Events are retrieved over HTTP by executing the Wai t Event manager action.
The following example shows how events can be retrieved using the Wai t Event manager
action. The steps are:
1. Start an HTTP AMI session using the Logi n action.
2. Register a SIP phone to Asterisk to generate a manager event.
3. Retrieve the manager event using the Wai t Event action.
The interaction looks like this:
$ wget - - save- cooki es cooki es. t xt \
>Hht t p: / / l ocal host : 8088/ mxml ?act i on=l ogi n&username=hel l o&secret =worl d" - 0 -
<aj ax- response>
<response type=' obj ect ' i d=' unknown' >
/mxml encoding
470 1 Chapter 20: Asterisk Manager Interface (AMI)
<generi c response=' Success' message=' Aut hent i cat i on accepted' / >
</ response>
</ aj ax- response>
$ wget --l oad-cooki es cooki es. txt "http: / / l ocal host: 8088/ mxml ?acti on=wai tevent" -O-
<aj ax- response>
<response type=' obj ect ' i d=' unknown>
<generi c response=' Success' message=' Wai t i ng f or Event compl eted. ' / >
</ response>
<response type=' obj ect ' i d=' unknown' >
<generi c event =' PeerSt at us' pri vi l ege=' syst em, al l
channel t ype= SI P' peer =' SI P/ OOOOFFFFOOO4
peerst at us=' Regi st ered' address=' l 72. 16.0.160:5060' / >
</ response>
<response t ype=' obj ect' i d=' unknown' >
<generi c event =' Wai t Event Compl et e' / >
</ response>
</ aj ax- response>
Development Frameworks
Many application developers write code that directly interfaces with the AMI. However,
there are a number of existing libraries that aim to make writing AMI applications
easier. Table 20-5 lists a few that we know are being used successfully. If you search
around for Asterisk libraries in any other popular programming language of your
choice, you are likely to find one that exists.
Table 20-5. AMI development frameworks
Framework Language URL
Adhearsion Ruby http-J/adhearsion.com/
StarPy Python http://starpy.sourceforge.net/
Asterisk-Java Java http-J/asterisk-java.org/
CSTA
Computer-Supported Telecommunications Applications (CSTA) is a standard for
Computer Telephony Integration (CTI). One of the biggest benefits of CSTA is that it
is used by mltiple manufacturers. Some of what is provided by CSTA can be mapped
to operations available in the AMI. There have been mltiple efforts to provide a CSTA
interface to Asterisk. One of these efforts is the Open CSTA (http://opencsta.org)
project. While none of the authors have experience with this CST A interface to Asterisk,
it is certainly worth considering if you have CSTA experience or an existing CSTA
application you would like to integrate with Asterisk.
Development Frameworks | 471
Interesting Applications
Many useful applications have been developed that take advantage of the AMI. Here
are a couple of examples.
AsteriskGUI
The AsteriskGUI is an open source PBX administration interface developed by Digium.
It is intended for use on small installations. The AsteriskGUI is written entirely in
HTML and JavaScript and uses the AMI over HTTP for all interaction with Asterisk.
It has been especially popular for use in resource-constrained embedded Asterisk en-
vironments, since it does not require additional software to run on the Asterisk server.
Figure 20-4 shows a page from the AsteriskGUI.
The AsteriskGUI can be obtained from the Digium subversin server:
$ svn co http: / / svn. di gi um. c0m/ svn/ asteri sk- gui / branches/ 2. O
It is also bundled as an option with the AsteriskNOW (http://www.asterisk.org/asteris
knowf) distribution.
Figure 20-4. AsteriskGUI
472 | Chapter 20: Asterisk Manager Interface (AMI)
Flash Operator Panel
Flash Operator Panel is an application that runs in a web browser using Flash. It is
primarily used as an interface to see which extensions are currently ringing or in use.
It also includes the ability to monitor conference room and cali queue status. Some cali
actions can be performed as well, such as barging into a cali and transferring calis.
Figure 20-5 shows a screenshot of the Flash Operator Panel interface.
Downloads and more detailed information on Flash Operator Panel can be found at
http://www.asternic.org.
No timeout
Extensin
rences
itme 901 Externa 1
Externa 2
9 Florencio fM 3 Pedro Externa 3
Sales Queue 14 Rodo
P| Support Queue ^yg^j fnl Externa 5 (
fSAdmin Queue f^DayMode
Figure 20-5. Flash Operator Panel
Conclusin
The Asterisk Manager Interface provides an API for monitoring events from an Asterisk
system, as well as requesting that Asterisk perform a wide range of actions. An HTTP
interface has been provided and a number of frameworks have been developed that
make it easier to develop applications. All of this information, as well as the examples
we looked at at the end of this chapter, should help get you thinking about what new
applications you might be able to build using the Asterisk Manager Interface.
Conclusin | 473

You might also like