Sunteți pe pagina 1din 201

What is Asterisk?

• Asterisk, The Open Source PBX. www.asterisk.org


• A complete PBX software
• Runs on Linux, BSD, MacOSX, and others
• Covers most VoIP protocols
• Many built-in features include voicemail, conferencing, IVR, queuing,
as well as standard calling functions
• Highly extensible - can handle virtually any task imaginable
• Many different hardware telephony cards are currently available
Asterisk History

• Originally developed by Mark Spencer starting around 1999


• He needed a flexible PBX for his Linux support company so he wrote
one himself
• he realised once a call is inside a PC, anything can be done with it -
hence the name Asterisk
• Met Jim Dixon from the Zapata telephony project in 2001, which
provided hardware and a business model for further development
• A thriving Asterisk development community
Asterisk Architecture
Architecture

Asterisk contains engines that perform critical functions. When Asterisk


starts, the Dynamic Module Loader loads and initializes drivers. The
drivers provide channel drivers, file formats, call detail recording back
ends, codecs, and applications, among others.

The Asterisk PBX Switching Core accepts telephone calls from the
interfaces. The Switching Core handles calls according to the
instructions found in a dial plan. The PBX Switching Core uses the
Application Launcher to ring phones, to connect to voicemail, or to dial
out on outbound trunks
Architecture

The PBX Switching Core includes a Scheduler and I/O Manager that is
available to drivers and applications. handles low-level task scheduling
and system management for optimal performance under all load
conditions

The Codec Translator seamlessly connects channels that compressed with


different codecs

Most of Asterisk's flexibility comes from the applications, codecs, channel


drivers, file formats and other facilities' interaction with the various
programming interfaces.
VoIP Signaling Protocols
VoIP Signaling Protocols

A signaling protocol is a common language spoken by telephones and call-


management servers, the PSTN, and legacy PBX systems as they
communicate to set up, monitor, and tear down calls.

The Voice over IP (VoIP) technology family provides several signaling


protocols. Asterisk support most of them but a few will be discussed
here:

 H.323
 SIP
 IAX
H.323
H.323 is an International Telecommunications Union Telecommunications
Standardization Sector (ITU-T) specification for transmitting
multimedia traffic, including video and voice, over an IP network

H.323 Protocols
Feature Protocol

Call Signalling H.225

Media Control H.245

Audio Codecs G.711, G.722, G.723, G.728, G.729

Video Codecs H.261, H.263

Data Sharing T.120

Media Transport RTP/RTCP


H.323 Elements

H.323 elements include terminals, gateways, gatekeepers and Multipoint


Control Units (MCUs).

Terminals
Also known as endpoints, terminals provide point-to-point and multipoint
conferencing for audio, video and data
Gateways
Gateways are used to connect between Switched Circuit Network (SCN)
endpoints and H.323 endpoints. Gateways are only needed when an
H.323 endpoint needs to interconnect to a different network
Gatekeeper
Gatekeepers provides pre-call and call-level control services to H.323
endpoints.
H.323 elements

Multipoint Controller (MC)


A Multipoint Controller supports conferencing between three or more
endpoints. A Multipoint Processor (MP) receives audio, video and data
streams, and then redistributes those streams to the endpoints in a
multipoint conference
The H.323 Call-Signaling Process

There are five general steps in the H.323 signaling process: setup/teardown,
capabilities negotiation, open media channel, perform call, and release.

Setup/Teardown
To initiate an H.323 call, H.225 is required for the setup process.
The following are the most commonly used signaling messages :
Setup: A forward message sent by a calling entity in an attempt to establish
a connection with the called entity
Proceeding: A backward message sent from the called entity to the calling
entity to inform that call establishment procedures were initiated
The H.323 Call-Signaling Process
Alerting: A backward message sent from the called entity to inform that called
party ringing was initiated
Connect: A backward message sent from the called entity to the calling entity
that the called party answered the call. The connect message can contain the
transport UDP/IP address for H.245 control signaling
Release: sent by endpoint initiating disconnect

Capabilities Negotiation
After setup, H.245 is enlisted to negotiate the call’s application requirements
H.245 determines:
-Which kind of application media each terminal can support: audio, video.
-Which codecs each terminal is capable of and which it may prefer
-How the media channel will be structured, and which packet interval will be
used
-Which terminal will be the master and which will be the slave for the duration
of the call. Master and slave roles distinguish the client/server role
assumptions for future signals during the call and are a protocol formality
The H.323 Call-Signaling Process
Open Media Channel
Once capabilities negotiation has succeeded, RTP Control Protocol (RTCP)
establishes a UDP socket for the media channel

Perform Call
As the call progresses, RTCP, which runs alongside RTP (usually on
separate, consecutive UDP ports that are selected during call setup), can
keep tabs on the media channel

Release
When the call concludes, H.225 enters its release state, signaling an end to
the media channel, an end to the H.245 application capabilities session,
and an end to the call-accounting transaction on the gatekeeper
Session Initiation Protocol (SIP)

Session Initiation Protocol (SIP) is an application-layer control protocol


used to create, modify and terminate a communication session

Sessions can include audio, video and data streams


SIP Overview

The two components in a SIP system are user agents and network servers.
Calling and called parties are identified by SIP addresses

User Agents
A SIP user agent is a client-end application continuing a User-Agent Client
(UAC) and a User-Agent Server (UAS.) These are known as a SIP client
and a SIP server. The client initiates SIP requests as a user's agent. A
server gets requests. A SIP server acts as a user's agent
SIP Overview
Network Servers
Two types of SIP servers proxy servers and redirect servers.

Proxy Servers
Act on behalf of other clients and contains both client and server functions.
a proxy server interprets and can rewrite request headers before passing
them on other servers. Rewriting ensures that the replies follow the same
path back to proxy instead of the client
Redirect Servers
Accepts SIP requests and sends a redirect response back to the client
containing the address of the next server
SIP Overview
Addressing
SIP Uniform Resource Locators (URLs) provide addressing similar to e-mail
addressing. A SIP URL can have various forms and can include a
telephone number, for example:

sip:someone@somewhere.com
sip:1-415-555-1212@somewhere.com
SIP Overview

SIP Methods and Responses


INVITE: Start sessions and advertise endpoint capabilities
ACK: Acknowledge to the called SIP peer that an INVITE has succeeded
BYE: This method is used when the call is completed
CANCEL: This method is used during attempts to override a prior request
that has not yet been completed
OPTIONS: Query a SIP peer for its capabilities information, without
actually establishing a media channel
REGISTER: This method notifies the SIP server at which endpoint a
particular user can be reached
SIP Overview
SIP Responses 482 Loop detected
Informational 486 Busy here
100 trying
180 Ringing
Server error
181 Call is being forwarded
182 Queued 500 Server internal error
502 Bad gateway
Success
200 Ok Global failure
300 Multiple choices 600 Busy everywhere
603 Decline
Client error
400 Bad request
401 Unathorized
403 Forbidden
408 Request timeout
SIP header
Headers are used to transport the information to the SIP entities.
The main fields are:

- Via: shows the transport protocol used and the request route, each
proxy adds a line to this field
- From: shows the address of the caller.
- To: show the called user address of the request.
- Call-Id: Unique identifier for each call and contains the host
address. It must be the same for all the messages within a transaction.
- Cseq: begins with a random number and it identifies in a sequential
way each message.
- Contact : shows one (or more) address than can be used to contact
the user
- User Agent: The client agent who deals the communication.
SIP header
Message Header
Via: SIP/2.0/UDP
192.168.0.100:5060;rport;branch=z9hG4bK646464100000007343c526790
00020a600000e45
Content-Length: 0
Call-ID: 911D32E5-EEDF-4572-B0B2-61B294636E88@192.168.0.100
CSeq: 1 ACK
From: "Prueba"<sip:20000@miasterisk.com>;tag=8922404614682
Max-Forwards: 70
Route: <sip:20001@192.168.0.1>
To: <sip:20001@miasterisk.com>;tag=as0a27b928
User-Agent: SJphone/1.60.289a (SJ Labs)
Contact: <sip:20100@192.168.0.100:5060>;expires=3600
Inter-Asterisk Exchange (IAX) Protocol

The Inter-Asterisk Exchange (IAX) Protocol is a signaling protocol for VoIP


networks, just like SIP and H.323. It also provides endpoint and trunk signaling

IAX is also NAT-proof, so dozens or hundreds of simultaneous calls from behind a


masquerading firewall will function correctly, just like HTTP.

IAX is much more compact because it has been developed only for telephony
applications

While a complete cycle of registration, call signaling, voice transmission, and tear-
down can use several TCP and UDP ports and connections with SIP or H.323,
IAX handles all of these functions using a single UDP port. When the IAX client
(endpoint) registers with the IAX server or proxy, this UDP port is utilized. This
same port is also utilized to place a call
Inter-Asterisk Exchange (IAX) Protocol

The way IAX distinguishes between registration, signaling, and voice


packets is by including headers and meta data in each packet
Asterisk’s Installation
Asterisk’s Installation

 Requirements
 Kernel source
 bison
 bison-devel
 ncurses
 ncurses-devel
 zlib
 zlib-devel
 openssl
 openssl-devel
 gnutls-devel
 gcc
 gcc-c++
Installation
Check the required packages: Install the packages if they are not
installed:
rpm -q kernel-devel
rpm -q bison
rpm -q bison-devel yum install kernel-devel
rpm -q ncurses yum install bison
rpm -q ncurses-devel yum install bison-devel
rpm -q zlib
rpm -q zlib-devel yum install ncurses
rpm -q openssl yum install ncurses-devel
rpm -q openssl-devel yum install zlib
rpm -q gnutls-devel
yum install zlib-devel
rpm -q gcc
rpm -q gcc-c++ yum install openssl
yum install openssl-devel
yum install gnutls-devel
yum install gcc
yum install gcc-c++
Installation

Voice over IP (VoIP) Scenarios

 Pure VoIP System


 Connecting Asterisk to PSTN
A Pure VoIP System
Installing a Pure VoIP Server
Files needed

 asterisk-1.4.x.tar.gz
 asterisk-addon-1.4.x.tar.gz
 asterisk-sounds-1.4.x.tar.gz
Installing a Pure VoIP Server
 Download required packages
 wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-
1.4.14.tar.gz
 wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-
addons-1.4.6.tar.gz

 wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-
sounds-1.2.1.tar.gz
 Installation
 Install mpg123 to play mp3 files for music-on-hold before Asterisk’s
installation
 wget http://mpg123.orgis.org/download/mpg123-1.2.0.tar.gz
 tar -zxvf mpg123-1.2.0.tar.gz
Installation
 cd mpg123-1.2.0
 ./configure
 make

 make install

 ln -s /usr/local/bin/mpg123 /usr/bin/mpg123

 Installing Asterisk
 tar -zxvf asterisk-1.4.14.tar.gz
 cd asterisk-1.4.14
 make clean
 ./configure
 make
 make install
 make samples
 make config
Installation
 Installing Asterisk’s Add-ons
 tar -zxvf asterisk-addon-1.4.6.tar.gz
 cd asterisk-addon-1.4.6
 make clean
 make
 make install
 Installing Asterisk’s Sounds
 tar -zxvf asterisk-sounds-1.2.6.tar.gz
 cd asterisk-sounds-1.2.6
 make
 make install
Connecting Asterisk to PSTN
Installation

Files needed

 libpri-1.4.x.tar.gz
 zaptel-1.4.x.tar.gz
 asterisk-1.4.x.tar.gz
 asterisk-addon-1.4.x.tar.gz
 asterisk-sounds-1.4.x.tar.gz
Installation
 Download required packages
 wget http://downloads.digium.com/pub/asterisk/old-releases/ asterisk-
1.4.14.tar.gz
 wget http://downloads.digium.com/pub/zaptel/releases/ zaptel-1.4.8.tar.gz
 wget http://downloads.digium.com/pub/libpri/releases/libpri-1.4.3.tar.gz

 wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-addons-
1.4.6.tar.gz
 wget http://downloads.digium.com/pub/asterisk/old-releases/asterisk-sounds-
1.2.1.tar.gz
Installation
 Installing libpri
 tar -zxvf libpri-1.4.3.tar.gz
 cd libpri-1.4.3
 make
 make install
 Installing zaptel
 tar -zxvf zaptel-1.4.8.tar.gz
 cd zaptel-1.4.8
 ./install_prereq test ;Check for dependencies
 ./install_prereq install ;Install dependencies if not installed
 ./configure
 make
 make install
 make config
 The remaining installation is similar to that of a pure VoIP Asterisk System
Starting and Managing Asterisk

 Asterisk can be started by typing:


 /usr/sbin/asterisk

 To connect to an Asterisk daemon, type:


 asterisk –r

 To make Asterisk more verbose, type:


 asterisk -vvvvvr
Connecting to Asterisk Console
Once connected to an Asterisk console, you will get:

Asterisk 1.4.14, Copyright (C) 1999 - 2007 Digium, Inc. and others.
Created by Mark Spencer <markster@digium.com>
Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for
details.
This is free software, with components licensed under the GNU General Public
License version 2 and other licenses; you are welcome to redistribute it under
certain conditions. Type 'core show license' for details.
===================================================================
======
Connected to Asterisk 1.4.14 currently running on localhost (pid = 3960)
Verbosity is at least 3
localhost*CLI>
Asterisk’s Console Commands
 Type the following commands on Asterisk’s console:

 help To have a list of all commands


 reload To reload the configuration
 stop To stop the Asterisk process
 exit To exit the command line interface
Asterisk Configuration files
Asterisk Configuration files

Asterisk.conf defines the locations for the configuration files, the spool directory, and
the modules, as well as a location to write log files to.

[directories]
astetcdir => /etc/asterisk ; location where Asterisk configuration
files are stored

astmoddir => /usr/lib/asterisk/modules ; location where Asterisk


modules are stored

astvarlibdir => /var/lib/asterisk ; location where Asterisk


libraries are stored
astagidir => /var/lib/asterisk/agi-bin ;location where agi scripts are
stored
astspooldir => /var/spool/asterisk ; location where all records are
stored
astrundir => /var/run ; location where Asterisk will store its PID file
astlogdir => /var/log/asterisk ; location where Asterisk logs are stored
Manager.conf
The Asterisk Manager interface is an API which external programs can
use to communicate with, and control, Asterisk.

[general]
enabled = no
port = 5038
bindaddr = 0.0.0.0

[magma]
secret = welcome
deny=0.0.0.0/0.0.0.0
permit= 192.168.1.0/255.255.255.0
read = system,call,log,verbose,command,agent,user
write = system,call,log,verbose,command,agent,user
cdr_custom.conf

Asterisk will generate a CDR for every finished call by default; this file
defines exactly what gets logged in this CDR line.

[mappings]
Master.csv =>
"${CDR(clid)}","${CDR(src)}","${CDR(dst)}","${CDR(dcontext)}","${CDR(c
hannel)}","${CDR(dstchannel)}","${CDR(lastapp)}","${CDR(lastdata)}",
"${CDR(start)}","${CDR(answer)}","${CDR(end)}","${CDR(duration)}","
${CDR(billsec)}","${CDR(disposition)}","${CDR(amaflags)}","${CDR(ac
countcode)}","${CDR(uniqueid)}","${CDR(userfield)}”
rtp.conf

The rtp.conf file controls the Real-time Transport Protocol (RTP) ports
that Asterisk uses to generate and receive RTP traffic.
[general]
rtpstart=10000
rtpend=20000
rtpchecksums=no
Sip.conf

[general} section
Implements settings on all SIP clients

Port
The port Asterisk should listen for SIP incoming clients. The default is
5060
Bindaddr
If the Asterisk machine has multiple IPs, this option tells Asterisk to
listen on a particular IP. Asterisk listens on all interfaces and aliases by
default
Context
The default context for SIP clients
Sip.conf

Type of Service (ToS)


Sets ToS bits in an IP header to improve performance on routers that
respects ToS bits
The options are low delay, throughput, reliability, mincost, none

Allow and disallow


Allows and disallows specific codecs.
Codec negotiation is attempted in the order in which codecs are defined.
The best practice is to disallow all and then allow a codec explicitly
For example:
disallow=all
allow=g729
allow=alaw
allow=ulaw
Sip.conf

Maxexpirey
The maximum amount of time until a peer’s registration expires

Defaultexpirey
This sets the default SIP registration expiration time, in seconds, for
incoming and outgoing registrations

Register
Register this Asterisk with another host
Sip.conf
Client Options

Type
The type option sets the connection class for the client. The options
are:
peer: A device which receives calls from an Asterisk server
user: A device that makes calls through an Asterisk server
friend: A device that can both send and receive calls through
an Asterisk server
Secret
Set a password for the client

Host
A client’s IP address. Can also be set to dynamic if a client comes
from any IP
Sip.conf
Defaultip
Asterisk will send a call on this IP if a host is set to dynamic and the
SIP client is not registered yet
Username
A client’s username
Context
The context to start in extensions.conf
Canreinvite
Connects end-points directly
Nat
Can be set to yes, no, or never. If set to yes, Asterisk ignores the IP
address in the SIP and SDP headers and responds to the address and
port in the IP header. The never option is for devices that cannot
handle rport in the SIP header, such as the Uniden UIP200.
Sip.conf

Qualify
Sets qualify to yes, no, or a time in milliseconds. If you set qualify=yes,
NOTIFY messages will be sent periodically to the remote peers to
determine whether they are available and what the latency between
replies is. A peer is determined unreachable if no reply is received
within 2,000 ms (to change this default, set qualify to the number of
milliseconds to wait for the reply). Use this option in conjunction with
nat=yes to keep the path through the NAT device alive.
Iax.conf
[general] section

Bandwidth
Instead of allowing or disallowing codecs, use low or high bandwidth
options to automatically select the low bandwidth consumption codec
or high bandwidth consumption codec
jitterbuffer
Turn the jitterbuffer on or off. The jitterbuffer is used to maximize audio
quality by balancing latency against the number of dropped packets
dropcount
Sets the maximum number of packets per memory size to be dropped in
order to reduce latency
maxjitterbuffer
Sets the maximum size of the jitterbuffer
Iax.conf

maxexcessjitterbuffer:
Sets the maximum excess jitterbuffer, which, if exceeded, causes the
jitterbuffer to slowly shrink in order to improve latency.
Simple Example
sip.conf extensions.conf
[internal]
[101] exten = > 101,1,Dial(SIP/101)
username=101 exten = > 102,1,Dial(SIP/102)
type = friend
secret = mypassword
qualify = yes
nat = no
host = dynamic
context = internal

[102]
username=102
type = friend
secret = mypassword
qualify = yes
nat = no
host = dynamic
context = internal
Configuring Soft Phone
select
Menu -> System Settings -> Sip Proxy -
> default
Configuring Hard Phone
Open a web browser and type the IP
address of IP phone
Click admin login -> Ext1
sip.conf
extensions.conf
[103]
[internal]
username=101
exten = > 103,1,Dial(SIP/103)
type = friend
exten = > 104,1,Dial(IAX2/104)
secret = mypassword
qualify = yes
nat = no
host = dynamic
context = internal

iax.conf
[104]
username=102
type = friend
secret = mypassword
qualify = yes
nat = no
host = dynamic
context = internal
Introduction To Dial Plan
Introduction To Dial Plan
Actual Asterisk Call Switching is performed by Dial Plan

Two Important files make up Dial Plan

extensions.conf
Based on priority model

extensions.ael
Based on asterisk extension language

The dial plan consists of four main parts: contexts, extensions, priorities, and
applications.
extensions.conf layout
Contents of extensions.conf is organized in three sections

 general

 global

 contents

general and global are setting sections


executable dial plan components are defined in contexts
`
[general] Section
Here we define few general options regarding dial plan
static
it indicates if a 'save dial plan' command from console is possiable. It works
with write protect. If set to no or omitted, pbx_config will rewrite this file and
all comments made in the file will be lost.
writeprotect
if static is yes and write protect=no the you can save dial plan by CLI
command 'save dial plan'.
autofallthrough
If autofallthrough is set, then if an extension runs out of things to do, it will
terminate the call with BUSY, CONGESTION or HANGUP depending on
Asterisk's best guess (strongly recommended).
If autofallthrough is not set, then if an extension runs out of
things to do, asterisk will wait for a new extension to be dialed
[general] Section
clearglobalvars
If clearglobalvars is set, global variables will be cleared and reparsed on an
extensions reload, or Asterisk reload. If clearglobalvars is not set, then global
variables will persist through reloads, and even if deleted from the
extensions.conf or one if its included files, will remain set to the previous
value."
global variables will be discussed in details later
Priorityjumping
If priorityjumping is set to 'yes', then applications that support 'jumping' to a
different priority based on the result of their operations will do so
Individual applications can also be requested to do this by passing a 'j' option
in their arguments.
[general] Section
#include "filename.conf"
Include other config files with the include command.
[global] Section
Dial plan global variables and their initial values are defined in this section.

Global variables are normally used as constants.

They are defined here so that they might be changed easily in the future.

Global variables will be discussed in detail later


[contexts] in extensions.conf
The Dial plan consists of a collection of contexts. Each context consists of a collection of
extensions which perform actual call routing.

Contexts will be discussed later.


extensions
An extension consists of the following parts:

 Extension (Name or number)


 Priority (a kind of program line number)

 Application - an instruction which tells Asterisk what it should do with the call

The syntax is:


exten => extension , priority, Command(parameters)
extensions
Extensions are of three types

 Literal
 Pattern

 Predefined
Literal
Literal extensions can contain numbers (0-9), letters A,B,C,D (some hard phones have
these letters) or all letters (a-z)

An example

exten => arif,1,Dial(SIP/arif)


Pattern
If an extension’s name starts with '_', it is considered as pattern

for pattern some characters have special meaning.


X any digit from 0-9
Z any digit from 1-9
N any digit from 2-9
[12679] any digit in the bracket for example 1,2,6,7,or 9
. (dot) wildcard, matches everything remaining.
[1-8] any digit in the range 1 to 8
Testing a Pattern
Using CLI command 'dialplan show' we *CLI> dialplan show
[ Context 'default' created by 'pbx_config'[
can test pattern.
Context 'my-phones' created by 'pbx_config' ]

'23' => 1. Answer() [pbx_config]

Example: 2. Playback(hello-world) [pbx_config] 3. Hangup()


[pbx_config]
extensions.conf
[ Context 'parkedcalls' created by 'res_features']

[my-phones]
'700' => 1. Park() [res_features]
exten => 23,1,Answer()
-= 2 extensions (4 priorities) in 3 contexts. =-
exten => 23,2,Playback(hello-world)  *CLI>

exten => 23,3,Hangup()


Testing a Pattern
dialplan show my-phones
dialplan show 23@my-phone
dialplan show 25@my-phones

Now change pattern to _2X

[my-phones]
exten => _2X,1,Answer()
exten => _2X,2,Playback(hello-world)
exten => _2X,3,Hangup()
Testing a Pattern
Test with the following CLI commands.

dialplan show 23@my-phone


dialplan show 25@my-phone
dialplan show 246@my-phones

now change pattern to _2X.

[my-phones]
exten => _2X.,1,Answer()
exten => _2X.,2,Playback(hello-world)
exten => _2X.,3,Hangup()
Testing a Pattern
Test with following CLI commands.

dialplan show 23@my-phones


dialplan show 25@my-phones
dialplan show 246@my-phones
Pattern matching order
Asterisk prioritizes patterns based on the quality of the match.
If two extensions match a dialed number, Asterisk will always chose the better match.
Before deciding which extension matches best, it processes the entire context.

Example:

[sales]
exten => _12X.,1,NoOp(12X)
exten => 12345,1,NoOp(12345)
exten => _1234.,1,NoOp(1234.)
Pattern matching
Testing

dial plan show 12345@sales


dial plan show 12346@sales

Pattern “_.” in Asterisk 1.2

Digium has changed the behaviour of “_.” as it was in Asterisk 1.2. it should have
lowest priority but in Asterisk 1.2 its behaviour is opposite to the expected
behaviour
Pattern matching
Example

[sales]
exten => _12X.,1,NoOp(12X)
exten => 12345,1,NoOp(12345)
exten => _1234.,1,NoOp(1234.)
exten => _.,1,NoOp(testing _.)

Testing:
dialplan show 12345@sales
In Asterisk 1.2:
show dialplan 12346@sales
Predefined
There are several predefined extension names:
- i - Invalid
- s - Start
- h - Hangup
- t - Timeout
- T - AbsoluteTimeout
- o – Operator

we ll discuss them later with examples


priorities
Priority is the order in which commands are run. First the one with priority 1, then with 2,
.
Asterisk does not consider the order in which you put the lines in the extensions.conf file. You can
mix the lines into a different order, like the following example, and it will make no difference
because Asterisk uses the priority of each line to determine the order of execution:

 [test]
exten => 555,4,Hangup
exten => 555,1,Answer
exten => 555,3,Voicemail(44)
exten => 555,2,Playback(tt-weasels)
n priority
n priority automatically increases a priority's value
using n priority its easy to insert new command without disturbing the original
priorities

Labels can be set using n priority, so that it can be targeted with goto
exten => s,n(start),Answer

Arbitrary increments can be defined


exten => s,n+2,Dial(SIP/101)
Applications
Answer([delay])
Answer the ringing channel. If delay is specified then asterisk will wait for the
specified number of milliseconds before answering the channel.
Hangup
Hangs up the channel
BackGround()
Plays a file while waiting for the user to begin entering an extension
PlayBack(filename)
Plays a given filename
Applications(cont.)
SayDitits()
Says the specified digits using the current language setting for the channel
Busy()
Request that the channel indicate the busy condition
Set(n=value)
Sets variable n to the specified value
Wait(seconds)
Wait for the specified number of seconds, then return 0.
WaitExten()
Waits for the user to enter a new extension for the specified amount of time then
return 0
Applications(cont.)
Goto([[context,]extension,]priority)

Sends control of the current channel to the ; same as above, but using a named priority
specified priority, optionally setting the exten => 124,1,Answer( )
destination’s extension and context
exten => 124,2,Set(COUNT=1)
exten => 123,1,Answer( )
exten =>
exten => 123,2,Set(COUNT=1)
124,3(repeat),SayNumber(${COUNT})
exten => 23,3,SayNumber(${COUNT})
exten => 124,4,Set(COUNT=$[${COUNT} + 1
exten => 123,4,Set(COUNT=$[${COUNT}
])
+ 1 ])
exten => 124,5,Goto(repeat)
exten => 123,5,Goto(3)
Applications(cont.)
GotoIf(condition?label1:label2) ; same thing as above, but this time we'll specify an extension and a
priority for each label

Sends the call to label1 if the condition is exten => 124,1,GotoIf($[ ${TEST} = 101]?123,10:123,20)

true, or to label2 if the condition is ; same thing as above, but these labels have a context, extension, and
priority
false.
exten => 125,1,GotoIf($[ ${TEST} = 101
]?incoming,123,10:incoming,123,20)
Either label1 or label2 may be omitted but
not both.

[globals]

TEST=101

[incoming]

; go to priority 10 if ${TEST} is 101, otherwise go to


priority 20

exten => 123,1,GotoIf($[ ${TEST} = 101 ]?10:20)

exten => 123,10,Playback(the-monkeys-twice)

exten => 123,20,Playback(tt-somethingwrong)


Applications(cont.)
GotoIfTime(times,days_of_week,days_of_month,months?label)

jumps to the specified label if current time matched with the specified time

; If we're open, then go to the open context

; We're open from 9am to 6pm Monday through Friday

exten => s,1,GotoIfTime(09:00-17:59,mon-fri,*,*?open,s,1)

; We're also open from 9am to noon on Saturday

exten => s,2,GotoIfTime(09:00-11:59,sat,*,*?open,s,1)

; Otherwise, we're closed

exten => s,3,Goto(closed,s,1)


Context
Context is a collection of extensions
Context can be used to implement some important features
Routing: Route call based on extension
Autoattendent: Greet callers and ask them to enter extensions
MultilevelMenus: Menus for sales, Support etc
Authentication: Ask for passwords for certain extensions
Day/Night: Vary behavior after hours
Example
[contex]
exten => some_exten,priority,application(arg1,arg2...)
exten => some_exten,priority,application(arg1,arg2...)
Context Example
[local1]
exten => _NX.,1,NoOp(Local call)

[countrywide]
include => local1
exten => _0N.,1,NoOp(Country Wide Call)

[international1]
include => local1
include => countrywide
exten => _00Z.,1,NoOp(International Call)
Variables
Variable is a placeholder for a value

Variables are referenced in dial plan as


${foo} ;foo is a variable name

Variables are of three types


 Global variables
 Channel variables
 Environment variables
Types of Variables
Global variables
Global variables apply to all extensions in all contexts
should be defined in global context
they can also be defined using SetGlobalVar() application
Channel Variables
Channel variables is associated only to a particual call
Channel variables are defined only for the duration of call
Channel variables are set via the set() application
Environment Variable
Environment variables are a way of accessing UNIX environment variables
these are referenced as ${ENV(var)} where var is UNIX environment variable.
Variable Example
Executing SetGlobalVar("Zap/1-1", "FOO=5") in new stack
[FooTest] ― Setting global variable 'FOO' to '5'
― Executing NoOp("Zap/1-1", "5") in new stack
exten => 100,1,SetGlobalVar(FOO=5) ― Executing NoOp("Zap/1-1", "5") in new stack
― Executing SetVar("Zap/1-1", "foo=8") in new stack
exten => 100,2,NoOp(${FOO}) ― Executing NoOp("Zap/1-1", "8") in new stack
― Executing NoOp("Zap/1-1", "8") in new stack
exten => 100,3,NoOp(${foo})

exten => 100,4,SetVar(foo=8)

exten => 100,5,NoOp(${FOO})

exten => 100,6,NoOp(${foo})


Inheritance of Channel
Variables
A variable name preceded by '_' character will cause that variable to be inherited by
channels created by the main channel

A variable preceded by a single '_' character will be inherited only once

A variable preceded by two '_' characters that is '__' will be inherited indefinitely
Inheritance of Channel
Variables
[variable-inheritance-test]

exten => 104,1,Set(FEE=fee)


exten => 104,2,Set(_FIE=fie)
exten => 104,3,Set(__FUM=fum)
exten => 104,4,Dial(Local/105@test1)

[test1]
exten => 105,1,NoOp(${FEE})
exten => 105,2,NoOp(${FIE})
exten => 105,3,NoOp(${FUM})
exten => 105,4,Dial(Local/106@test2)

[test2]
exten => 106,1,NoOp(${FEE})
exten => 106,2,NoOp(${FIE})
Some Predefined Channel Variables

${CHANNEL} current channel name


${EXTEN} current extension
${PRIORITY} current priority
${CONTEXT} current context
${EPOCH} current UNIX style epoch (no. of seconds since 1 jan
1970)
${DIALSTATUS} status of call
${DIALTIME} time since number was dialed
${ANSWEREDTIME} actual amount of time in seconds
${DATETIME} current date time(DDMMYY-HH:MM:SS) deprecated
in Asterisk 1.2, instead use STRFTIME
${TIMESTAMP} current date and time (YYYYMMDD-HHMMSS)
deprecated in Asterisk 1.4, , instead use STRFTIME
${CALLERID(num)} current caller ID number
Macros
A macro is a kind of subroutine
A macro is used to avoid repitation in dialplan
A macro is an extension context preceded by “macro-” for example [macro-voicemail]
commands are same as in context but with a few exceptions
Only s extension is allowed in macros
The original ${EXTEN} and ${CONTEXT} cannot be used. ${MACRO_EXTEN} and
${MACRO_CONTEXT} variables are used instead.
A macro is called with macro() application in an extension. Syntax is
Macro(macroname,arg1,arg2...)
[localcalls]
exten => _NX.,1,Macro(test,${EXTEN})

[nationwide]
include => localcalls
exten => _0N.,1,Macro(test,${EXTEN})

[intercalls]
include => localcalls
include => nationwide
exten => _00Z.,1,Macro(test,${EXTEN}

[macro-test]
exten => s,1,GoToIf($["${MACRO_CONTEXT}":"localcalls"] ?local)
exten => s,n,GoToIf($["${MACRO_CONTEXT}":"nationwide]" ?nation)
exten => s,n,NoOp(interntional call)
exten => s,n,hangup()
exten => s,n(local),NoOp(local calls)
Include
For simplifying and organising larger dial plans.
With include, we use other contexts in current context
The following is syntax of include statement
include => context ;where context is name of contex
first asterisk will look in the current context for match. If finds no match, then asterisk
looks in first included context then second and so on.
Include statement can be made conditional to the time of the day. This make it easier to
implement different day and night behaviors.
Example
[time-based]
include => open|09:00-17:00|mon-fri|*|*
include => open|09:00-14:00|sat|*|*
include => closed
[open]
exten => _X.,1,NoOp(Ofice Open)
[closed]
exten => _X.,1,NoOp(Office Closed)
Dial Command
Dial command sends call on one or more channels
if priorityjumping=yes, the the dial plan jumps to priority+101 on busy, congested and on
channel unavailable.
Syntax is
Dial(type1/identifier [&type2/identifier2 [&type3/identifier3...]],timeout,options,URL
type specifies channel type such as ZAP, SIP, IAX2 and so on
identifierspecifies “phone number” to dial on that channel
specify more than one channel for dial command using & sign.
Timeout optional parameter, defines timeout
Dial Command
Options
t: allow called user to transfer call
T: allow the calling user to transfer
r: generate ringing tone
m: provide music on hold to calling party until called channel answers
h: allow the called person to hangup by dialing *
H: allow the caller to hangup by dialing *
o: send the caller's ID
j: Asterisk v.1.2 jump to priority n+101 if all of the requested channels are busy
M(x): executes the macro(x) once call connects
Dial Command
g: when the called party hangs up, exit to execute more commands in the current
context
G(context^exten^pri) if call is answered, transfer both parties to the specified context
and extension
S(n): hang up the call after n seconds of answer call
Return Codes of Dial Command
Dial sets DIALSTATUS to indicate its success or failure
DIALSTATUS contains the following text string

ANSWER a sucessful dial


BUSY the number is busy
NOANSWER the number rang but no one answer the call
CANCEL dial command reached the number but the caller
handup before the called person picked up
CONGESTION congestion usually means number is not recognized
CHANUNAVAIL channel unavailable
Example
[dialstatus-test]

exten => 200,1,Dial(SIP/802,5,g)


exten => 200,n,NoOp(Dialstatus:${DIALSTATUS})

exten => 201,1,Dial(SIP/801,5,g)


exten => 201,n,NoOp(Dialstatus:${DIALSTATUS})
Special Extensions
Some additional system defined extensions are:
h: hangup, this extension is called when a caller hangs up the phone. When this
extension is called channel related variables get destroyed
Example:
[exten-h-testing]
include => from-internal1
exten => 200,1,GoTo(from-internal1,s,1)
[from-internal1]
exten => s,1,Set(CONNECTIONS=$[${CONNECTIONS}+1]|g)
exten => s,2,NoOp(${CONNECTIONS})
exten => s,3,wait(210)
exten => h,1,Set(CONNECTIONS=$[${CONNECTIONS}-1])
Special Extensions
i: I extension is executed when a caller enters an invalid extension. I extension only
works with background(). Channel variables get destroyed when I is called

O and a extension
Call will be directed to operater if caller presses 0 and if operater=yes in voicemail.conf
• Will direct call to a extension (abort)
Special Extensions
T and t extension
t
If there is no input in an IVR menu within a certain timeframe, the t extension is
called

T
The T extension is called after the absolute timeout has been exceeded. You can set
this timeout value with Set(TIMEOUT(absolute)=<seconds>)
Special Extensions
The timer starts whenever the timeout value is set (it does not automatically start with
the connection, it must be started explicitly with the Set() command).
Example:
exten => 20,1,Answer()
exten => 20,2,Set(TIMEOUT(absolute)=120)
exten => 20,3,Playback(hello-world)
exten => 20,4,Wait(1)
exten => 20,5,Goto(3)

exten => T,1,Wait(1)


exten => T,2,Playback(thank-you-for-calling)
exten => T,3,Wait(1)
exten => T,4,Hangup()
Special Extensions
s extension
For any scenario in which we cannot determine the number dialed, use the s
extension.
exten => s,1,Answer()
exten => s,2,Wait(1)
exten => s,3,Play(tt-monkeys)
exten => s,4,Wait(1)
exten => s,5,Hangup()
Expressions
Expressions are combinations of variables, operators, and values that you put together to
get a result

In Asterisk, expressions always begin with a dollar sign and an opening square bracket and
end with a closing square bracket, as shown below:
$[expression]

When Asterisk encounters an expression in a dial plan, it replaces the entire expression
with the resulting value.

Example

exten => 321,1,Set(COUNT=3)


exten => 321,2,Set(NEWCOUNT=$[${COUNT} + 1])
exten => 321,3,SayNumber(${NEWCOUNT})
Expressions
Operators

types of operators that are available in Asterisk

Boolean operators

These operators evaluate the "truth" of a statement


The Boolean operators are:

expr1 | expr2
expr1 & expr2
expr1 {=, >, >=, <, <=, !=} expr2
Asterisk Features
Asterisk Database (AstDB)
Database data are grouped in families and identified with a key that is
unique within the family. AstDB’s structure is similar to the following:

Family1
Key1 => value
Key2 => value
:
:
Keyn => value
Family2
Key1 => value
Key2 => value
Asterisk Database’s Applications
Applications:
DBput
DBget
DBdel
DBdeltree

Dbput
Stores value in the database
Dbput(family/key=${foo}) (deprecated)
Set(DB(family/key)=${foo}) (new syntax)
CLI Command
CLI*>database put family key
Asterisk Database’s Applications
Dbget
Retrieve a value from the database
Dbget(foo=family/key) (deprecated)
Set(foo=${DB(family/key)})
CLI Command
CLI*>database get family key
Dbdel
Delete a key from the database
Dbdel(family/key)
CLI Command
CLI*>database del
Asterisk Database’s Applications
Dbdeltree
Delete a family or key tree from the database
Dbdeltree(family/keytree)
Call Forwarding
Forward the incoming call to some other number, or forward the
incoming call to some other number in case of busy or unavailable

Two types of abbreviations are used:

 Call Forward IMdiate (CFIM)


 Call Forward on BuSy (CFBS)
Call Forwarding
An example of call forwarding:
[apps]
;
; Unconditional Call Forward
;
; create call forward
exten => _*21*X.,1,GotoIf($${EXTEN:-1} = #?2:3)
exten => _*21*X.,2,StripLSD(1)
exten => _*21*X.,3,DBput(CFIM/${CALLERIDNUM}=${EXTEN:4})
exten => _*21*X.,4,Hangup
;
; delete call forward
exten => **21,1,DBdel(CFIM/${CALLERIDNUM})
exten => **21,2,Hangup
;
; delete call forward (with #)
exten => **21#,1,Goto(**21,1)
[macro-stdexten]
;
; Standard extension macro (with call forwarding):
; ${ARG1} - Extension(we could have used ${MACRO_EXTEN} here as well
; ${ARG2} - Device(s) to ring
;
exten => s,1,Set(temp=${DB(CFIM/${ARG1})})
exten => s,n,GotoIf(${temp}?cfim:nocfim)
exten => s,n(cfim),Dial(Local/${temp}@default) ; Unconditional forward
exten => s,n(nocfim),NoOp
exten => s,n,Dial(${ARG2},15) ; 15sec timeout
exten => s,n,Set(temp=${DB(CFBS/${ARG1})})
exten => s,n,GotoIf(${temp}?cfbs:nocfbs)
exten => s,n(cfbs),Dial(Local/${temp}@default/n) ; Forward on busy or unavailabl
e
exten => s,n(nocfbs),Busy
Fowarding
[forward-test]

exten => *21*,1,PlayBack(thanks)


exten => *21*,2,read(for)
exten => *21*,3,Set(DB(CFIM/${CALLERID(num)})=${for})

exten => 801,1,Macro(callforward,${EXTEN})


[macro-callforward]

exten => s,1,Set(temp=${DB(CFIM/${ARG1})})


exten => s,n,GotoIf(${temp}?cfim:nocfim)
exten => s,n(cfim),Dial(SIP/${temp})
exten => s,n,hangup
;Unconditional forwardÂ
exten => s,n(nocfim),Dial(SIP/${ARG1})
Call Monitoring

Taps into a phone call between a caller and a callee. This is possible
with:

 ChanSpy()
 ZapBarge()
 ExtenSpy()

ChanSpy()
Example
While spying
Dialing # cycles the volume
Dialing * will stop spying and look for another channel to spy on
Call Monitoring
ZapBarge()
Listens in on a conversation on a zap channel. If a channel is not
specified, it will prompt for one

Example
Exten => 8159,1,ZapBarge()
Exten => 8159,2,Hangup()

If you dial 8159, you are asked which line you want to listen on; for zap/1-
1 you will press 1# and for zap/25-1 you will press 25#
Call Monitoring
ExtenSpy()
Listen in on a channel, and also whisper into it if necessary

Example
[snoop]
exten => _555/705,1,ExtenSpy(|v(4))

[705]
exten => 705,1, dail(IAX2/trunk_3)
include => snoop
Call Monitoring
Add the following lines in extensions.conf

exten => *898,1,Answer


exten => *898,2,Wait(1)
exten => *898,3,Goto(spy,s,1)
exten => *898,4,Hangup

[spy]

exten => s,1,BackGround(please-enter-the)


exten => s,n,BackGround(extension)
exten => s,n,Set(TIMEOUT(digit)=5)
exten => s,n,Set(TIMEOUT(response)=10)
exten => s,n,WaitExten(10)
exten => _XXXX,1,ChanSpy(SIP/${EXTEN}|q)
Call Transfer
Transfer a call-in-progress to another destination. There are two types of
transfers:

 Supervised Call Transfer


 Blind Call Transfer

Features.conf settings:

blindxfer => #1
disconnect => *0
atxfer => *2
Call Parking
Places a call on-hold onto a specific parking location so that it can be
picked up by another extension

Features.conf
Parkext => 700
Parkpos => 701-720
Context => parkedcall
Parkingtime => 45
Route by Caller ID
exten => 123/100,1,Answer()
exten => 123/100,2,Playback(tt-weasels)
exten => 123/100,3,Voicemail(123)
exten => 123/100,4,Hangup()
MeetMe Conferencing

MeetMe conferencing can be configured in two steps:

• Configure the meetme.conf file


• Call a conference from extension.conf using the MeetMe application
meetme.conf

The syntax is:


Conf => conference_number [,pin] [,administrative_pin]

Example:
Conf => 2222,1821, 191871

where
2222 is a room number
1821 is a password
19187 is an administrative password
MeetMe() Application

Enter into a conference configured in meetme.conf


The format is:
MeetMe([cong_no][,[options][,pin]])
Conf_no is the conference number to join

The options can be any of the following:


m Monitor mode. Only listening, no talking
t Talk mode. Only talking, no listening
I Announce who is joining/leaving
P A user can exit by pressing the # key
E Select the first empty PIN-less conference
r Conversation will be recorded in the format
${MEETME_RECORDINGFORMAT} and saved as
${MEETME_RECORDINGFILE}
C Upon entering, announce how many users are in a conference
M Music-on-hold will be played when there is only one user in the
conference
x Close the conference when the last marked user exits
S Enter menu(user & administrator) when the * key is pressed
P Always ask for a PIN even if it is specified

If a PIN argument is specified, the caller must enter that PIN in order to
enter the conference
An Example

[globals]
CONFMAX => 10 ; maximum persons in conference

exten => 8081,1,Macro(stdmeetme,8081))

[macro-stdmeetme]
; with limit to maximum number of persons in conference

exten => s,1,MeetMeCount(${MACRO_EXTEN}|count)


exten => s,2,Gotoif,$[${count} >= ${CONFMAX}]?103
exten => s,3,MeetMe(${MACRO_EXTEN})
exten => s,4,Goto(s|1)

exten => s,103,Background(conf-full)


exten => s,104,Hangup
Voicemail

Voicemail can be configured by configuring three files:

• Configure voicemail.conf
• Call the mailbox configured in voicemail.conf from extensions.conf
• Define the mailbox for the user in sip/iax/zapata.conf
voicemail.conf

Voicemail.conf contains one general section, one zonemessages section


and one or more user-defined sections. Its layout is:

[general]
Setting=value

[zonemessages]
Newzonename=country/city|options

[context_section]
User-defined contexts here
voicemail.conf

 The general section holds global configurations

 The zonemessages section defines the time-zone and time-reporting


formats

 The user-defined context contains the mailbox’s definition


[general] Section

Externnotify Supplies the full path and filename of an external


program to be executed when a voicemail is left or
delivered, or when a mailbox is checked
Externpass The path of the external program to be executed after
voicemail’s password is changed
Silencethreshold When using the maxsilence setting, eliminate background
noise by adjusting the silence detection’s threshold
Servermail Source e-mail address
Maxmsg Limits the number of messages in the voicemail folder
Minmessage Eliminate a message shorter than the time in seconds
specified. The default is zero, which indicates no minimum
time
Format The voice messages’ format i.e. wav49, GSM and wav
Maxgreet Limits a user’s recordable voicemail greeting
Skipms Interval, in milliseconds, to use to skip forward or reverse
while playing voicemail messages
[general] Section

The general section’s configuration settings are:

Attach Copy voicemail as an audio file and send via e-mail as


an attachment
Delete After sending an e-mail, delete voicemail after
notification. Works with Attach, and can be used while
defining the mailbox as:
823 => 1234,office,office@abc.com,attach=yes|delete=1
Mailcmd Program used by Asterisk to send an e-mail, for
example:
mailcmd=/usr/sbin/sendmail -v -t –f pbx@abc.com
Maxsilence Indicates how many seconds of silence to allow before
ending the recording
[general] Section

Pbxskip Changes the subject line in a voicemail notification


message. Takes values yes or no. If yes, the Subject: line
will be: “Subject: New message M in mailbox B".
When set to no, the Subject: line will read, "Subject:
[PBX]: New message M in mailbox B"
Fromstring Overrides a portion of the From: line in a voicemail
notification message. The default is “From: Asterisk PBX”
Emailsubject Defines an e-mail subject, for example:
emailsubject=New voicemail in mailbox
${VM_MAILBOX} from ${VM_CALLERID}
Emailbody An example:
emailbody=\n\tHi ${VM_NAME},\n\n\tYou have a
${VM_DUR} long new voicemail message (number
${VM_MSGNUM}) in mailbox ${VM_MAILBOX}\nfrom
${VM_CIDNAME} (${VM_CIDNUM}), on
${VM_DATE}\nso
you might want to check it when you get a chance.\n\n
[general] Section

Context An optional context when a user presses the # key or 0


to exit voicemail
Nextaftercmd If set to yes, the system will automatically play the next
message after deleting a voicemail message
[zonemessages] Section

Define time-zones for different users in the [zonemessages] section, and


assign voicemail boxes to use the setting for one of these zones later.
The syntax is:
Zonename= timezone|time_format
Zonename is the name used to identify the zone
Timezone is the name of the system time zone as found in
/usr/share/zoneinfo
Time_format specifies how the voicemail system should announce the
times
The Time_format argument is composed of the following elements:
Filename The filename of the sound file
$(VAR) Variable substitution
A or a The day of the week (Saturday, Sunday, etc.)
B or b or h The name of the month (January, February, etc.)
[zonemessages] Section

D or e The numeric day of the month (First, second, etc.)


Y Year
I or I Hour, 12-hour clock
H Hour, 24-hour clock (single digit hours preceded by an
oh)
K Hour, 24-hour clock (single digit hours not preceded by
an oh)
M Minutes
P or p AM or PM
Q Today, yesterday
R 24-hour time, including minutes
[zonemessages] Section

Examples:

12-hours Pacific Standard Time


San-diego=America/Tijuana|’vm-received’Q’digits/at’IMP

24-hours Pacific Standard Time


San-diego=America/Tijuana|’vm-received’Q’digits/at’R
[context] Section

The format is:


Extension_number => voicemail_password,user_name,
user_email_address, user_pager_email_address, user_options

Options override the settings in the default section. Attach, servermail,


tz, saycid, review, operater, callbak, dialout and exitcontext are
defined here:

Tz defines the time-zone setting as defined in the zonemessages section.


For example:
123 => 2048, abc_user, abc@osrc.org.pk,,tz=sandiego|attach=yes
Extensions.conf Applications
VoiceMail()

The format is:


VoiceMail(boxnumber [@context] ] [&boxnumber2 [@context]], [flags])

Record the audio file in the given box number which may be specified in
voicemail.conf. The flags can be any of the following:

s Skip an instruction such as “Please leave a message ……..”


u Cause an unavailable message to be played
b Cause the busy message to be played
g(#) Adjust the gain of the recording. The # key is gain in decibels
Note: Do not specify u & b together
Extensions.conf Applications

VMSTATUS is the channel variable which will be set after completion.


The possible values are:
SUCCESS|USEREXIT|FAILED

The path of stored voice messages is:


/var/spool/asterisk/voicemail/context/boxnumber/INBOX/

VoiceMailMain()
Enter the main voicemail system to check voicemail. The format is:
VoicemailMain([[s]mailbox]@context)

If s is specified, then the password check will be skipped. If a context is


specified, then a login in that context will be considered
Sip/iax/zapata.conf Configuration

Define the mailbox’s parameter for the user. For example:

Mailbox=1234
or
Mailbox=1234@context
Flite
Flite (festival-lite) is a small, fast run-time synthesis engine
asterisk-flite is a Flite text-to-speech module for the Asterisk open-
source PBX.
Flite
cd /tmp
wget http://asterisk-flite.sourceforge.net/extras/flite-1.3-sharedlibs.patch
wget http://asterisk-flite.sourceforge.net/extras/flite-1.3-alsa_support.patch
wget http://www.speech.cs.cmu.edu/flite/packed/flite-1.3/flite-1.3-release.tar.gz
wget http://kent.dl.sourceforge.net/sourceforge/asterisk-flite/asterisk-flite-
0.5.tar.gz
tar -zxvf flite-1.3-release.tar.gz
rm -f flite-1.3-release.tar.gz
cd flite-1.3-release
patch -p1 < ../flite-1.3-sharedlibs.patch
patch -p1 < ../flite-1.3-alsa_support.patch
./configure --enable-shared
make
make install
Flite
cd ../
tar -xzvf asterisk-flite-0.5.tar.gz
rm -f asterisk-flite-0.5.tar.gz
mv asterisk-flite-0.5 flite-1.3-release/
cd flite-1.3-release/asterisk-flite-0.5
make
make install
Verify that there is now a app_flite.so file in /usr/lib/asterisk/modules/
nano /etc/ld.so.conf
make sure that /usr/local/lib is in there. Add it if need be and save file.
ldconfig
asterisk -rx 'restart now'
asterisk -r
show application Flite
Flite
to test it, I simply put it in your extensions.conf file:

exten => 123,1,Flite(this is a test.)


Asterisk ACD

 Routes calls in a call center environment to appropriate agents, based


on skill-sets, time available and priority level

 To configure ACD we need to configure queues.conf, agents.conf,


extensions.conf and sip/iax/zapata.conf
queues.conf

If an agent is busy placing a call in a queue, the queues are configured in


the queue.conf file

Sections of a queue.conf file: The general section supports only


persistent members. If set to yes and if a member is added to the
system via the AddQueueMember() application, the application will
be stored in AstDB and retained when restarting

 Periodicannounce
Periodicannounce and periodic-announce-frequency plays messages
such as “Thank you for holding ….” at regular intervals
 Weight
Assign a rank to the queue. If calls are waiting in multiple queues, then
the queue with the highest weight values will be presented to agents
first.
 Leavewhenempty
To remove callers from a queue when no agent is present, set this option
to yes
 Wrapuptime
Allow a few seconds’ break to an agent after completing a call
 Memberdelay
Delay between the time when a queue identifies a free agent and when
the call is connected to that agent
 Timeoutrestart
If set to yes, then the timeout for an agent is reset if a BUSY or
CONGESTION is received

Strategy to distribute calls

ringall Ring all available channels


roundrobin Use the first available channel, then the second and so
on. Deprecated in 1.4; use rrmemory instead
leastrecent Ring the interface least recently called by this queue
fewestcalls Ring the interface handling the fewest calls from this
queue
random Ring randomly
rrmemory Round robin with memory. Remember where we left off
the last ring pass
 Timeout
Timeout in seconds when calling an agent
Announce
Play a file to an agent before the caller is connected. Useful for agents
who are logged into more than one queue
member => member_name
Members of queue
For example
member => agent/@1 a group
member => agent/501 single agent
Monitor-format
Record all completed calls. Possible values are wav, gsm, wav49
Monitor-join
If set to yes, it is an indication to merge the two files
Extensions.conf application

Queue()
Format is
Queue(queuename[|options[|URL][|announceoverride][|timeout]])
queuename name of the context in queue.conf
Options:
t Allow the called user to transfer the call
T Allow the calling user to transfer the call
h Allow the called person to hangup by pressing *
H Allow the calling person to hangup by pressing *
n Forbid retries if there is a timeout. Exit and move to next
extension
r Ring instead of music-on-hold
URL Send a URL to the called user if a channel supports this facility
Announceoverride
Set a sound file to override the one set in queues.conf
Timeout
Maximum time to wait in queue. The next extension will be executed
after the timeout
agents.conf

Configures agents for the queues

The [general] section contains only one parameter, which is


persistentagents. This option specifies whether the agent call-back
logins have to be stored in an Asterisk database or not.

The following parameters define the agents:

autologoff How long the phone has to ring without answering


before an agent is logged off
ackall If an agent is logging with agentcallbacklogin, then an
acknowledgement is required by pressing the # sign if
this option is yes
Wrapuptime Time after the conversation is over
Musiconhold Define the music-on-hold class
Updatecdr Change the source channel in cdr to
agent/agent- id to determine which agent generated
the call
Group Group agents for easy management
group=groupnumber example
group =1
agent => 888,888,user1
Custom-beep Accepts the filename as an argument. Notifies
an agent about an incoming call
Recordagentcalls Accept the argument yes or no.
Specifies whether an agent’s calls should
be recorded or not
Recordformat Specifies the recording format (wav49, gsm or wav)
Savecallsin Specifies the path to store recordings
Urlprefix String appended to the start of the text to be added to
the recording’s name

Creation of agent
Format is
Agent => agentnumber, agent_password, name
Agent_number is an agent’s number
Agent_password is an agent’s password
Name is an agent’s actual name
Extensions.conf application

AgentLogin()
Logs an agent to receive calls. An agent can hang-up a call by pressing
the * key
Format is
AgentLogin([AgentNo][,options])
The Option argument contains s, which causes the login to be silent
Example
Exten => 123,1,AgentLogin(42,s)
AgentCallbackLogin()
Format is
AgentCallbackLogin([AgentNo|][exten]@context)
This application asks the agent to login to the system with call back
[ivr-test]

exten => 8000,1,VoiceMailMain(802@mb-test)


exten => _X.,1,Goto(ivr,s,1)
[ivr]
exten => s,1,Answer()
exten => s,n,Set(TRIES=0)
exten => s,n(playback),background(please-enter-your)
exten => s,n,WaitExten(5)

exten => 800,1,SayDigits(800)

exten => 801,1,SayDigits(801)

exten => 802,1,Dial(SIP/802,10)


exten => 802,n,NoOp(dialstatus:${DIALSTATUS})
exten => 802,n,NoOp(exten:${EXTEN})
exten => 802,n,Goto(s-${DIALSTATUS},1)

exten => s-NOANSWER,1,VoiceMail(802@mb-test)


exten => s-NOANSWER,2,Playback(vm-goodbye)
exten => s-NOANSWER,3,wait(2)
exten => s-NOANSWER,4,hangup()

exten => s-CONGESTION,1,Congestion


exten => s-CANCEL,1,Hangup
exten => s-BUSY,1,Busy
exten => s-CHANUNAVAIL,1,VoiceMail(802@mb-test)
exten => s-CHANUNAVAIL,2,Playback(vm-goodbye)
exten => t,1,PlayBack(vm-sorry)
exten => t,n,Set(TRIES=$[${TRIES}+1])
exten => t,n,GoToIf($["${TRIES}" > "2"]?disconnect)
exten => t,n,GoTo(s,playback)
exten => t,n(disconnect),Hangup()

exten => i,1,PlayBack(vm-sorry)


exten => i,n,Set(TRIES=$[${TRIES}+1])
exten => i,n,GoToIf($["${TRIES}" > "2"]?disconnect)
exten => i,n(abc),GoTo(s,playback)
exten => i,n(disconnect),Hangup()
Connecting to PSTN
Connecting to PSTN
A Public Switched Telephone Network (PSTN) has two types of
connections:

• Analogue Connections
• Digital Connections
Analogue Connections
FXO cards are used to connect Asterisk with PSTN using analogue
phone lines and FXS cards are used to connect analogue phones to
Asterisk

FXO and FXS Channels

• FXO Accepts a dial tone


• FXSGenerates a dial tone and provides ringing voltage to alert the
user
Analogue Hardware used with Asterisk
Digium’s hardware:

Digium TDM400P (4 Ports maximum)


Digium TDM800P (8 Ports maximum)
Digium TDM2400P (24 Ports maximum)

Sangoma:

Sangoma A200 Configurator (24 Ports maximum)


Sangoma A400 Configurator (48 Ports maximum)
Rhino FXO and FXS cards
Openvox FXO and FXS Cards
Zaptel’s Hardware
Configuration
zaptel.conf is located in /etc and this file is used to configure hardware.
For example:

fxsks=2
loadzone=us
defaultzone=us

The card is FXO, therefore FXS with kewlstart signaling is defined for
channel 2. There can be any of the following three signals:

Loopstart Indicates on hook/off hook and ring/no ring


Kewlstart Based on a loop start, but also indicates that the other side
has disconnected the call
Loadzone Configure a set of indications to use for the channel as
defined in zonedata.c

Defaultzone The default zone is used if no zone is specified for a


channel

Loading Drivers
Use the modprobe command. For example, the wctdm is the driver for
Digium TDM400P

modprobe wctdm

No output means that the driver has been loaded successfully. To


unload it, type:

rmmod wctdm
Verify the configuration:

1. Ztcfg is used to verify the hardware’s and ports’ configuration

#/sbin/ztcfg –vv

An error message indicates that the channel has been configured for the
wrong signaling

2. Zttool is a diagnostic program which can also be used to determine


the hardware’s state
Zapata’s Hardware Configuration

After configuring zaptel.conf, the modules are loaded, but Asterisk is


unaware of any hardware

Zapata.conf is used to set and configure telephony hardware

It tells Asterisk to use hardware and control its associate features


zapata.conf

signalling Sets the channel’s signalling type, which should match


the zaptel driver’s configurations. Can hold one of the
four values: fxs_ks, fxo_ks, pri_cpe or pri_net

ISDN PRI Switch Configuration

switchtype Type of PRI switch


overlapdial Whether Asterisk can dial this switch using overlap
digits, i.e., in case of DDI
Analogue Handset Features

Immediate Connects without providing a dial tone, just like


PLAR
callwaiting If enabled, Asterisk will generate "call waiting pips"
Callwaitingcallerid Sets whether Asterisk will send a caller’s ID data to
the handset during a call-waiting indication
threewaycalling If enabled, you can place a call on hold by pressing
a hook flash, whereupon you get a dialrecall tone
and can make another call. The default is no
threewaycalling=yes
transfer This option is activated only when
threewaycalling=yes. If threewaycalling=yes and
transfer=yes, then once you've placed a call on hold
with a hook flash, you can transfer that call to
another extension by dialing the extension and
hanging up. The default is no
cancallforward If enabled, activate "call forwarding immediate" by
dialling *72. Disable the call forwarding by dialing
*73. The default is no
callreturn If enabled, dial *69 to have Asterisk read the caller
ID of the last person to call you
Callgroup A channel may belong to zero or more callgroups.
Callgroups specify who will answer this
phone when it is ringing.If this channel is ringing,
then any other channel whose pickupgroups
include one of this channel's callgroups may answer
the call by dialing *8#. Zap, SIP, Skinny and
MGCP channels support this feature. group=1
callgroup=1,2,3
Pickupgroup Pickupgroups specify whose phones you may
answer. If another channel is ringing, and this
channel's pickupgroups include one of the ringing
channel's callgroups, then this channel may answer
the call by dialing *8#.
group=1
pickupgroup=3,4
Caller ID Options

Callerid Sets the Caller ID string forward to the recipient when


calls come in from this channel. This is normally used to set
the Caller ID for handsets.For trunk lines, set to
"asreceived" to pass the received Caller ID forward:

callerid="Mark Spencer" <256 428-6000>


Usecallerid This option causes Asterisk to send Caller ID data to the
handset when ringing it. For trunk lines, this option causes
Asterisk to look for Caller ID on incoming calls
Hidecallerid (Not for FXO trunk lines) For PRI channels, this will stop
the sending of Caller ID on outgoing calls. For FXS
handsets, this will stop Asterisk from sending this
channel's Caller ID information to the called party when
you make a call using this handset. FXS handset users may
enable or disable the sending of their Caller ID for the
current call only by lifting the handset and dialing *82
(enable) or *67 (disable)
Audio Quality Tuning Options

echocancel Disable or enable echo cancellation.


The default is yes
echocancelwhenbridged Enables or disables echo cancellation
during a bridged TDM call.
Echotraining In some cases, the echo canceller
doesn't train quickly enough and
there is an echo at the beginning of
the call which then quickly fades out.
Enabling echo training will cause
Asterisk to briefly mute the channel,
send an impulse, and use the
impulse’s response to pre-train the
echo canceller so that it can start out
with a much more accurate concept
of the actual echo
Important

Context This specifies which context a call will start in:


context=internal
Channel This keyword causes Asterisk to actually allocate a
channel with the settings that have been specified
earlier on in the file. Each channel definition will
inherit all the options stated ahead of it in this file.
Allocating a channel will not "clear" the settings, so any
channels defined later on in this file will inherit the
options for this channel unless you override its
settings:

channel => 16
channel => 2,3
channel => 1-8
[trunkgroups]
; define any trunk groups
[channels]
; hardware channels
; default
usecallerid=yes
hidecallerid=no
callwaiting=no
threewaycalling=yes
transfer=yes
echocancel=yes
echotraining=yes
; define channels
context=incoming ; Incoming calls go to [incoming] in extensions.conf
signalling=fxs_ks ; Use FXS signalling for an FXO channel
channel => 2 ; PSTN attached to port 2
Digital Connections

Primary Rate Interface (PRI)

ISDN connections are delivered in two variants, Primary Rate


Interface (PRI) and Basic Rate Interface (BRI)

PRI is the standard for connections to offices. It's based on a T1 line in


the US,
and an E1 line in Europe. The T1 PRI consists of 24 channels, the E1
PRI of 32.

The number of PRI channels varies from country to country.


In North American and Japan it is 23B + 1D (23 64Kbps digital
channels + 1 64Kbps signalling/control channel) on a T1 1.544 Mbps
In Europe and Australia it is 30B + 2D on an E1 2.048 Mbps
Channel 0 is used for synchronization and channel 16 is used for
signalling.
E1 and T1

T1 Services
T1 service can be provided as channelized or unchannelized. There
are 24 channels in the channelized T1 version. Each channel can be a
telephone call. T1 gives you 24 phone lines in place of the 23 that can
be accommodated with PRI. However, since there is no separate
signaling channel, the signaling information which indicates when a
phone is on the hook or off the hook is carried within each channel
by using or "robbing" the least significant bit. Unfortunately,
channelized T1 does not provide any capability for ANI or caller ID
data. PRI service is required for that purpose.

Unchannelized T1 treats all 24 T1 line channels as one big combined


channel for carrying Internet service, point-to-point data download or
VoIP broadband phone. This service is intended to be handled by
digital routers, not PBX telephone systems. No dedicated phone
channels or signaling is assigned for switched telephone service.
Digital Hardware

Digium’s Digital TDM Cards

TE411P - 4 span T1/E1/J1 Card with Hardware Echo Cancellation for 3.3v
PCI
TE410P - 4 span T1/E1/J1 Card for 3.3v PCI
TE406P - 4 span T1/E1/J1 Card with Hardware Echo Cancellation for 5v
PCI
TE405P - 4 span T1/E1/J1 Card for 5v PCI
TE210P - 2 span T1/E1/J1 Card for 3.3v PCI
TE205P - 2 span T1/E1/J1 Card for 5v PCI
TE110P - 1 span T1/E1/J1 Card for 3.3v or 5v PCI

Sangoma
A104
A104
Configuring Digium’s Digital Hardware

Zaptel.conf configurations for Digium’s digital hardware are as follows:

Span
Span format is
Span = (spannum),(timing),(LBO),(framing),(coding)
spannum Number of span. Begins with 1 and goes up in integers.
No two spans can have the same span number
Timing How to synchronize the timing device
0: Use as sync source. Send timing synchronization to
other end
1: To use as primary sync source
2: To set as secondary sync source and so forth
Line Build Out (LBO) A cable’s length between a zap card and a
smartjack/telecom-provided modem. In case
of a long cable, use 0

Framing How to communicate with the hardware at the


other end

For T1: Framing is d4 or esf


For E1: Framing is cas or ccs

Coding line encoding setting


For T1: Coding is ami or b8zs
For E1: Coding is ami or hdb3
Example:
span=1,1,0,esf,b8zs
First zaptel span receiving timing from other end, cable is less than 133
feet, uses esf framing and b8zs line encoding

span=2,2,0,ccs,hdb3,crc4
This is the second span on the system, has second priority to receive
timing from the other end, cable is less than 133 feet, uses ccs framing
and hdb3 line encoding.crc-4 is error checking
Zaptel.conf
span=1,1,0,esf,b8zs
bchan=1-23
dchan=24

Zapata.conf

switchtype=national
context=blah
signalling=pri_cpe
group=1
channel => 1-23
Asterisk Real time
Asterisk Real time

Asterisk Real time allows the storage of users/peers data to be stored in a


database
You do not need to reload configurations after you make the changes.
Setup and Configurations

 If want to use MySQL with Asterisk then install the MySQL database,
client libraries and header.

 Install Asterisk Real Time driver, which can be found in the Asterisk
distribution’s add-ons section.
Installing MySQL
cd /usr/src
wget http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.33.tar.gz
tar -zxvf mysql-5.0.33.tar.gz
cd mysql-5.0.33
groupadd mysql
useradd -g mysql mysql
./configure –prefix = /usr/local/mysql
make
make install
Scripts/mysql_install_db
chown -R root /usr/local/mysql
chown -R mysql /usr/local/mysql/var
chgrp -R mysql /usr/local/mysql

cp Support-files/my-medium.cnf /etc/my.cnf
Installing MySQL
Start MySQL:

/usr/local/mysql/bin/mysql_safe &

Create a symbolic link:

mkdir /var/lib/mysql
cd /var/lib/mysql
ln -s /tmp/mysql.sock

Install the mysql-devel:

yum install mysql-devel


Installing Asterisk Real Time driver
wget http://downloads.digium.com/pub/asterisk/old-releases/ asterisk-1.4.1x.tar.gz
tar -zxvf asterisk-addon-1.4.x.tar.gz
cd asterisk-addon-1.4.x

To enable the unique ID in Asterisk’s cdrs, add the following line in Makefile:

vi Makefile

CFLAGS += -DMYSQL_LOGUNIQUEID

Add the following line on top of cdr_addon_mysql.c

#define MYSQL_LOGUNIQUEID
Installing Asterisk Real Time driver
Compile and install:

make clean
make
make install

Copy the configuration files to the /etc/asterisk directory:

cp cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
cp res_mysql.conf.sample /etc/asterisk/res_mysql.conf
Configuring Database
mysql --user=root –password=password

CREATE DATABASE asteriskcdrdb;

GRANT ALL
ON asetriskcdrdb.*
TO asteriskuser@localhost
IDENTIFIED BY 'yourpassword';
Configuring Database
Create table cdr
USE asteriskcdrdb;
CREATE TABLE `cdr` (
`calldate` datetime NOT NULL default '0000-00-00 00:00:00',
`clid` varchar(80) NOT NULL default '',
`src` varchar(80) NOT NULL default '',
`dst` varchar(80) NOT NULL default '',
`dcontext` varchar(80) NOT NULL default '',
`channel` varchar(80) NOT NULL default '',
`dstchannel` varchar(80) NOT NULL default '',
`lastapp` varchar(80) NOT NULL default '',
`lastdata` varchar(80) NOT NULL default '',
`duration` int(11) NOT NULL default '0',
`billsec` int(11) NOT NULL default '0',
`disposition` varchar(45) NOT NULL default '',
`amaflags` int(11) NOT NULL default '0',
`accountcode` varchar(20) NOT NULL default '',
`userfield` varchar(255) NOT NULL default ''
);
ALTER TABLE `cdr` ADD INDEX ( `calldate` );
ALTER TABLE `cdr` ADD INDEX ( `dst` );
ALTER TABLE `cdr` ADD INDEX ( `accountcode` );

The unique ID has been enabled. Enter the following command:


ALTER TABLE `cdr` ADD `uniqueid` VARCHAR(32) NOT NULL default '' after `accountcode`;
Configuring Database
Create Asterisk Real Time Database:

CREATE DATABASE asteriskrealtime;

GRANT ALL
ON asetriskrealtime.*
TO asteriskuser@localhost
IDENTIFIED BY 'yourpassword';

Create Table for SIP Extensions:


USE asteriskrealtime;
CREATE TABLE sip_buddies ( ………………………………………………………..)
Connecting Asterisk CDRs With Database
Edit the configuration files. Edit cdr_mysql.conf

[global]
hostname=127.0.0.1
dbname=asteriskcdrdb
table=cdr
password='your password'
user=asteriskuser
Connecting Asterisk With Database
Edit res_mysql.conf

[general]
dbhost = 127.0.0.1
dbname = asteriskrealtime
dbuser = asteriskuser
dbpass = yourpassword
dbport = 3306
dbsock = /var/lib/mysql/mysql.sock
Connecting Asterisk With Database
Edit the /etc/asterisk/extconfig.conf as given below:

[settings]
sipusers => mysql,asterisk,sip_buddies
sippeers => mysql,asterisk,sip_buddies
extensions => mysql,asterisk,extensions

S-ar putea să vă placă și