linux slides
TRANSCRIPT
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 wroteone 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, whichprovided hardware and a business model for further development• A thriving Asterisk development community
Asterisk Architecture
Architecture
Asterisk contains engines that perform critical functions. When Asteriskstarts, the Dynamic Module Loader loads and initializes drivers. Thedrivers provide channel drivers, file formats, call detail recording backends, codecs, and applications, among others.
The Asterisk PBX Switching Core accepts telephone calls from theinterfaces. The Switching Core handles calls according to theinstructions found in a dial plan. The PBX Switching Core uses theApplication Launcher to ring phones, to connect to voicemail, or to dialout on outbound trunks
Architecture
The PBX Switching Core includes a Scheduler and I/O Manager that isavailable to drivers and applications. handles low-level task schedulingand system management for optimal performance under all loadconditions
The Codec Translator seamlessly connects channels that compressed withdifferent codecs
Most of Asterisk's flexibility comes from the applications, codecs, channeldrivers, file formats and other facilities' interaction with the variousprogramming 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 theycommunicate to set up, monitor, and tear down calls.
The Voice over IP (VoIP) technology family provides several signalingprotocols. Asterisk support most of them but a few will be discussedhere:
H.323SIP IAX
H.323H.323 is an International Telecommunications Union Telecommunications
Standardization Sector (ITU-T) specification for transmittingmultimedia traffic, including video and voice, over an IP network
H.323 ProtocolsFeature 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 MultipointControl Units (MCUs).
TerminalsAlso known as endpoints, terminals provide point-to-point and multipoint
conferencing for audio, video and dataGatewaysGateways are used to connect between Switched Circuit Network (SCN)
endpoints and H.323 endpoints. Gateways are only needed when anH.323 endpoint needs to interconnect to a different network
GatekeeperGatekeepers 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 datastreams, and then redistributes those streams to the endpoints in amultipoint 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/TeardownTo 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 entityProceeding: 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 ProcessAlerting: A backward message sent from the called entity to inform that called
party ringing was initiatedConnect: A backward message sent from the called entity to the calling entity
that the called party answered the call. The connect message can contain thetransport UDP/IP address for H.245 control signaling
Release: sent by endpoint initiating disconnect
Capabilities NegotiationAfter setup, H.245 is enlisted to negotiate the call’s application requirementsH.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 roleassumptions for future signals during the call and are a protocol formality
The H.323 Call-Signaling ProcessOpen Media ChannelOnce capabilities negotiation has succeeded, RTP Control Protocol (RTCP)
establishes a UDP socket for the media channel
Perform CallAs the call progresses, RTCP, which runs alongside RTP (usually on
separate, consecutive UDP ports that are selected during call setup), cankeep tabs on the media channel
ReleaseWhen 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 protocolused 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 AgentsA 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 clientand a SIP server. The client initiates SIP requests as a user's agent. Aserver gets requests. A SIP server acts as a user's agent
SIP OverviewNetwork ServersTwo types of SIP servers proxy servers and redirect servers.
Proxy ServersAct on behalf of other clients and contains both client and server functions.
a proxy server interprets and can rewrite request headers before passingthem on other servers. Rewriting ensures that the replies follow the samepath back to proxy instead of the client
Redirect ServersAccepts SIP requests and sends a redirect response back to the client
containing the address of the next server
SIP OverviewAddressingSIP Uniform Resource Locators (URLs) provide addressing similar to e-mail
addressing. A SIP URL can have various forms and can include atelephone number, for example:
SIP Overview
SIP Methods and ResponsesINVITE: Start sessions and advertise endpoint capabilitiesACK: Acknowledge to the called SIP peer that an INVITE has succeededBYE: This method is used when the call is completedCANCEL: This method is used during attempts to override a prior request
that has not yet been completedOPTIONS: Query a SIP peer for its capabilities information, without
actually establishing a media channelREGISTER: This method notifies the SIP server at which endpoint a
particular user can be reached
SIP Overview
SIP ResponsesInformational100 trying180 Ringing181 Call is being forwarded182 Queued
Success200 Ok300 Multiple choices
Client error400 Bad request401 Unathorized403 Forbidden408 Request timeout
482 Loop detected486 Busy here
Server error500 Server internal error502 Bad gateway
Global failure
600 Busy everywhere603 Decline
SIP headerHeaders are used to transport the information to the SIP entities.
The main fields are:
- Via: shows the transport protocol used and the request route, eachproxy 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 hostaddress. It must be the same for all the messages within a transaction.- Cseq: begins with a random number and it identifies in a sequentialway each message.- Contact : shows one (or more) address than can be used to contactthe user- User Agent: The client agent who deals the communication.
SIP headerMessage Header
Via: SIP/2.0/UDP192.168.0.100:5060;rport;branch=z9hG4bK646464100000007343c52679000020a600000e45Content-Length: 0Call-ID: [email protected]: 1 ACKFrom: "Prueba"<sip:[email protected]>;tag=8922404614682Max-Forwards: 70Route: <sip:[email protected]>To: <sip:[email protected]>;tag=as0a27b928User-Agent: SJphone/1.60.289a (SJ Labs)Contact: <sip:[email protected]:5060>;expires=3600
Inter-Asterisk Exchange (IAX) Protocol
The Inter-Asterisk Exchange (IAX) Protocol is a signaling protocol for VoIPnetworks, 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 amasquerading firewall will function correctly, just like HTTP.
IAX is much more compact because it has been developed only for telephonyapplications
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. Thissame port is also utilized to place a call
Inter-Asterisk Exchange (IAX) Protocol
The way IAX distinguishes between registration, signaling, and voicepackets 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:
rpm -q kernel-develrpm -q bisonrpm -q bison-develrpm -q ncursesrpm -q ncurses-develrpm -q zlibrpm -q zlib-develrpm -q opensslrpm -q openssl-develrpm -q gnutls-develrpm -q gccrpm -q gcc-c++
Install the packages if they are notinstalled:
yum install kernel-devel
yum install bisonyum install bison-devel
yum install ncursesyum install ncurses-devel
yum install zlibyum install zlib-devel
yum install opensslyum install openssl-devel
yum install gnutls-develyum 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 ServerFiles needed
asterisk-1.4.x.tar.gzasterisk-addon-1.4.x.tar.gzasterisk-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 <[email protected]>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 undercertain 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, andthe 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 Asteriskmodules are stored
astvarlibdir => /var/lib/asterisk ; location where Asterisklibraries are stored
astagidir => /var/lib/asterisk/agi-bin ;location where agi scripts arestored
astspooldir => /var/spool/asterisk ; location where all records arestored
astrundir => /var/run ; location where Asterisk will store its PID fileastlogdir => /var/log/asterisk ; location where Asterisk logs are stored
Manager.confThe Asterisk Manager interface is an API which external programs can
use to communicate with, and control, Asterisk.
[general]enabled = noport = 5038bindaddr = 0.0.0.0
[magma]secret = welcomedeny=0.0.0.0/0.0.0.0permit= 192.168.1.0/255.255.255.0read = system,call,log,verbose,command,agent,userwrite = system,call,log,verbose,command,agent,user
cdr_custom.conf
Asterisk will generate a CDR for every finished call by default; this filedefines exactly what gets logged in this CDR line.
[mappings]Master.csv =>
"${CDR(clid)}","${CDR(src)}","${CDR(dst)}","${CDR(dcontext)}","${CDR(channel)}","${CDR(dstchannel)}","${CDR(lastapp)}","${CDR(lastdata)}","${CDR(start)}","${CDR(answer)}","${CDR(end)}","${CDR(duration)}","${CDR(billsec)}","${CDR(disposition)}","${CDR(amaflags)}","${CDR(accountcode)}","${CDR(uniqueid)}","${CDR(userfield)}”
rtp.conf
The rtp.conf file controls the Real-time Transport Protocol (RTP) portsthat Asterisk uses to generate and receive RTP traffic.
[general]rtpstart=10000rtpend=20000rtpchecksums=no
Sip.conf
[general} sectionImplements settings on all SIP clients
PortThe port Asterisk should listen for SIP incoming clients. The default is5060
BindaddrIf the Asterisk machine has multiple IPs, this option tells Asterisk tolisten on a particular IP. Asterisk listens on all interfaces and aliases bydefault
ContextThe default context for SIP clients
Sip.conf
Type of Service (ToS)Sets ToS bits in an IP header to improve performance on routers thatrespects ToS bitsThe options are low delay, throughput, reliability, mincost, none
Allow and disallowAllows 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 explicitlyFor example:disallow=allallow=g729allow=alawallow=ulaw
Sip.conf
MaxexpireyThe maximum amount of time until a peer’s registration expires
DefaultexpireyThis sets the default SIP registration expiration time, in seconds, forincoming and outgoing registrations
RegisterRegister this Asterisk with another host
Sip.confClient Options
TypeThe type option sets the connection class for the client. The optionsare:
peer: A device which receives calls from an Asterisk serveruser: A device that makes calls through an Asterisk serverfriend: A device that can both send and receive calls through
an Asterisk serverSecret
Set a password for the client
HostA client’s IP address. Can also be set to dynamic if a client comesfrom any IP
Sip.conf
DefaultipAsterisk will send a call on this IP if a host is set to dynamic and theSIP client is not registered yet
UsernameA client’s username
ContextThe context to start in extensions.conf
CanreinviteConnects end-points directly
NatCan be set to yes, no, or never. If set to yes, Asterisk ignores the IPaddress in the SIP and SDP headers and responds to the address andport in the IP header. The never option is for devices that cannothandle rport in the SIP header, such as the Uniden UIP200.
Sip.conf
QualifySets qualify to yes, no, or a time in milliseconds. If you set qualify=yes,NOTIFY messages will be sent periodically to the remote peers todetermine whether they are available and what the latency betweenreplies is. A peer is determined unreachable if no reply is receivedwithin 2,000 ms (to change this default, set qualify to the number ofmilliseconds to wait for the reply). Use this option in conjunction withnat=yes to keep the path through the NAT device alive.
Iax.conf[general] section
BandwidthInstead of allowing or disallowing codecs, use low or high bandwidthoptions to automatically select the low bandwidth consumption codecor high bandwidth consumption codec
jitterbufferTurn the jitterbuffer on or off. The jitterbuffer is used to maximize audio
quality by balancing latency against the number of dropped packetsdropcountSets the maximum number of packets per memory size to be dropped in
order to reduce latencymaxjitterbufferSets 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
[101]
username=101
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
extensions.conf
[internal]
exten = > 101,1,Dial(SIP/101)
exten = > 102,1,Dial(SIP/102)
Configuring Soft PhoneselectMenu -> System Settings -> Sip Proxy -
> default
Configuring Hard PhoneOpen a web browser and type the IP
address of IP phoneClick admin login -> Ext1
sip.conf
[103]
username=101
type = friend
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
extensions.conf
[internal]
exten = > 103,1,Dial(SIP/103)
exten = > 104,1,Dial(IAX2/104)
Introduction To Dial Plan
Introduction To Dial PlanActual 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, andapplications.
extensions.conf layoutContents 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] SectionHere we define few general options regarding dial plan
static
it indicates if a 'save dial plan' command from console is possiable. It workswith write protect. If set to no or omitted, pbx_config will rewrite this file andall comments made in the file will be lost.
writeprotect
if static is yes and write protect=no the you can save dial plan by CLIcommand 'save dial plan'.
autofallthrough
If autofallthrough is set, then if an extension runs out of things to do, it willterminate the call with BUSY, CONGESTION or HANGUP depending onAsterisk'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] Sectionclearglobalvars
If clearglobalvars is set, global variables will be cleared and reparsed on anextensions reload, or Asterisk reload. If clearglobalvars is not set, then globalvariables will persist through reloads, and even if deleted from theextensions.conf or one if its included files, will remain set to the previousvalue."
global variables will be discussed in details later
Priorityjumping
If priorityjumping is set to 'yes', then applications that support 'jumping' to adifferent priority based on the result of their operations will do so
Individual applications can also be requested to do this by passing a 'j' optionin their arguments.
[general] Section#include "filename.conf"
Include other config files with the include command.
[global] SectionDial 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.confThe 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.
extensionsAn 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)
extensionsExtensions are of three types
Literal
Pattern
Predefined
LiteralLiteral 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)
PatternIf 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 PatternUsing CLI command 'dialplan show' we
can test pattern.
Example:
extensions.conf
[my-phones]
exten => 23,1,Answer()
exten => 23,2,Playback(hello-world)
exten => 23,3,Hangup()
*CLI> dialplan show
[ Context 'default' created by 'pbx_config'[
Context 'my-phones' created by 'pbx_config' ]
'23' => 1. Answer() [pbx_config]
2. Playback(hello-world) [pbx_config] 3. Hangup()
[pbx_config]
[ Context 'parkedcalls' created by 'res_features']
'700' => 1. Park() [res_features]
-= 2 extensions (4 priorities) in 3 contexts. =-
*CLI>
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 PatternTest 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 PatternTest with following CLI commands.
dialplan show 23@my-phones
dialplan show 25@my-phones
dialplan show 246@my-phones
Pattern matching orderAsterisk 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 matchingTesting
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 havelowest priority but in Asterisk 1.2 its behaviour is opposite to the expectedbehaviour
Pattern matchingExample
[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
PredefinedThere are several predefined extension names:
- i - Invalid
- s - Start
- h - Hangup
- t - Timeout
- T - AbsoluteTimeout
- o – Operator
we ll discuss them later with examples
prioritiesPriority 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 canmix the lines into a different order, like the following example, and it will make no differencebecause Asterisk uses the priority of each line to determine the order of execution:
[test]exten => 555,4,Hangupexten => 555,1,Answerexten => 555,3,Voicemail(44)exten => 555,2,Playback(tt-weasels)
n priorityn priority automatically increases a priority's valueusing 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 gotoexten => s,n(start),Answer
Arbitrary increments can be definedexten => s,n+2,Dial(SIP/101)
ApplicationsAnswer([delay])Answer the ringing channel. If delay is specified then asterisk will wait for the
specified number of milliseconds before answering the channel.HangupHangs up the channelBackGround()Plays a file while waiting for the user to begin entering an extensionPlayBack(filename)Plays a given filename
Applications(cont.)SayDitits()Says the specified digits using the current language setting for the channelBusy()Request that the channel indicate the busy conditionSet(n=value)Sets variable n to the specified valueWait(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
specified priority, optionally setting the
destination’s extension and context
exten => 123,1,Answer( )
exten => 123,2,Set(COUNT=1)
exten => 23,3,SayNumber(${COUNT})
exten => 123,4,Set(COUNT=$[${COUNT}
+ 1 ])
exten => 123,5,Goto(3)
; same as above, but using a named priority
exten => 124,1,Answer( )
exten => 124,2,Set(COUNT=1)
exten =>
124,3(repeat),SayNumber(${COUNT})
exten => 124,4,Set(COUNT=$[${COUNT} + 1
])
exten => 124,5,Goto(repeat)
Applications(cont.)GotoIf(condition?label1:label2)
Sends the call to label1 if the condition is
true, or to label2 if the condition is
false.
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)
; same thing as above, but this time we'll specify an extension and apriority for each label
exten => 124,1,GotoIf($[ ${TEST} = 101]?123,10:123,20)
; same thing as above, but these labels have a context, extension, andpriority
exten => 125,1,GotoIf($[ ${TEST} = 101]?incoming,123,10:incoming,123,20)
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)
ContextContext is a collection of extensionsContext can be used to implement some important featuresRouting: Route call based on extensionAutoattendent: Greet callers and ask them to enter extensionsMultilevelMenus: Menus for sales, Support etcAuthentication: Ask for passwords for certain extensionsDay/Night: Vary behavior after hoursExample[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 => local1exten => _0N.,1,NoOp(Country Wide Call)
[international1]include => local1include => countrywideexten => _00Z.,1,NoOp(International Call)
VariablesVariable 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 VariablesGlobal variablesGlobal variables apply to all extensions in all contextsshould be defined in global contextthey can also be defined using SetGlobalVar() applicationChannel VariablesChannel variables is associated only to a particual callChannel variables are defined only for the duration of callChannel variables are set via the set() applicationEnvironment VariableEnvironment variables are a way of accessing UNIX environment variablesthese are referenced as ${ENV(var)} where var is UNIX environment variable.
Variable Example[FooTest]
exten => 100,1,SetGlobalVar(FOO=5)
exten => 100,2,NoOp(${FOO})
exten => 100,3,NoOp(${foo})
exten => 100,4,SetVar(foo=8)
exten => 100,5,NoOp(${FOO})
exten => 100,6,NoOp(${foo})
Executing SetGlobalVar("Zap/1-1", "FOO=5") in new stack― Setting global variable 'FOO' to '5'― Executing NoOp("Zap/1-1", "5") in new stack― Executing NoOp("Zap/1-1", "5") in new stack― Executing SetVar("Zap/1-1", "foo=8") in new stack― Executing NoOp("Zap/1-1", "8") in new stack― Executing NoOp("Zap/1-1", "8") in new stack
Inheritance of ChannelVariables
A variable name preceded by '_' character will cause that variable to be inherited bychannels 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 ChannelVariables
[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 jan1970)
${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) deprecatedin 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
MacrosA macro is a kind of subroutineA macro is used to avoid repitation in dialplanA macro is an extension context preceded by “macro-” for example [macro-voicemail]commands are same as in context but with a few exceptionsOnly s extension is allowed in macrosThe 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 isMacro(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)
IncludeFor simplifying and organising larger dial plans.With include, we use other contexts in current contextThe following is syntax of include statementinclude => context ;where context is name of contexfirst 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 CommandDial command sends call on one or more channelsif priorityjumping=yes, the the dial plan jumps to priority+101 on busy, congested and on
channel unavailable.Syntax isDial(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 CommandOptionst: allow called user to transfer callT: allow the calling user to transferr: generate ringing tonem: provide music on hold to calling party until called channel answersh: allow the called person to hangup by dialing *H: allow the caller to hangup by dialing *o: send the caller's IDj: Asterisk v.1.2 jump to priority n+101 if all of the requested channels are busyM(x): executes the macro(x) once call connects
Dial Commandg: when the called party hangs up, exit to execute more commands in the current
contextG(context^exten^pri) if call is answered, transfer both parties to the specified context
and extensionS(n): hang up the call after n seconds of answer call
Return Codes of Dial CommandDial sets DIALSTATUS to indicate its success or failureDIALSTATUS contains the following text string
ANSWER a sucessful dialBUSY the number is busyNOANSWER the number rang but no one answer the callCANCEL dial command reached the number but the caller
handup before the called person picked upCONGESTION congestion usually means number is not recognizedCHANUNAVAIL 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 ExtensionsSome 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 destroyedExample:[exten-h-testing]include => from-internal1exten => 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 Extensionsi: 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 extensionCall will be directed to operater if caller presses 0 and if operater=yes in voicemail.conf• Will direct call to a extension (abort)
Special ExtensionsT and t extensiontIf there is no input in an IVR menu within a certain timeframe, the t extension is
called
TThe T extension is called after the absolute timeout has been exceeded. You can setthis timeout value with Set(TIMEOUT(absolute)=<seconds>)
Special ExtensionsThe 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 Extensionss extensionFor 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 toget a result
In Asterisk, expressions always begin with a dollar sign and an opening square bracket andend with a closing square bracket, as shown below:
$[expression]
When Asterisk encounters an expression in a dial plan, it replaces the entire expressionwith the resulting value.
Example
exten => 321,1,Set(COUNT=3)exten => 321,2,Set(NEWCOUNT=$[${COUNT} + 1])exten => 321,3,SayNumber(${NEWCOUNT})
ExpressionsOperators
types of operators that are available in Asterisk
Boolean operators
These operators evaluate the "truth" of a statementThe Boolean operators are:
expr1 | expr2expr1 & expr2expr1 {=, >, >=, <, <=, !=} expr2
Asterisk Features
Asterisk Database (AstDB)
Database data are grouped in families and identified with a key that isunique within the family. AstDB’s structure is similar to the following:
Family1Key1 => valueKey2 => value::Keyn => valueFamily2Key1 => valueKey2 => value
Asterisk Database’s Applications
Applications:DBputDBgetDBdelDBdeltree
DbputStores value in the databaseDbput(family/key=${foo}) (deprecated)Set(DB(family/key)=${foo}) (new syntax)CLI CommandCLI*>database put family key
Asterisk Database’s Applications
DbgetRetrieve a value from the databaseDbget(foo=family/key) (deprecated)Set(foo=${DB(family/key)})CLI CommandCLI*>database get family keyDbdelDelete a key from the databaseDbdel(family/key)CLI CommandCLI*>database del
Asterisk Database’s Applications
DbdeltreeDelete a family or key tree from the databaseDbdeltree(family/keytree)
Call Forwarding
Forward the incoming call to some other number, or forward theincoming 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 ForwardingAn example of call forwarding:[apps]
;; Unconditional Call Forward;; create call forwardexten => _*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 forwardexten => **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 forwardexten => 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 unavailableexten => 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 possiblewith:
ChanSpy()ZapBarge()ExtenSpy()
ChanSpy()ExampleWhile spyingDialing # cycles the volumeDialing * will stop spying and look for another channel to spy on
Call MonitoringZapBarge()Listens in on a conversation on a zap channel. If a channel is not
specified, it will prompt for one
ExampleExten => 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 MonitoringExtenSpy()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 MonitoringAdd the following lines in extensions.conf
exten => *898,1,Answerexten => *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 TransferTransfer a call-in-progress to another destination. There are two types of
transfers:
Supervised Call TransferBlind Call Transfer
Features.conf settings:
blindxfer => #1disconnect => *0atxfer => *2
Call ParkingPlaces a call on-hold onto a specific parking location so that it can be
picked up by another extension
Features.confParkext => 700Parkpos => 701-720Context => parkedcallParkingtime => 45
Route by Caller IDexten => 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
where2222 is a room number1821 is a password19187 is an administrative password
MeetMe() Application
Enter into a conference configured in meetme.confThe 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 talkingt Talk mode. Only talking, no listeningI Announce who is joining/leavingP A user can exit by pressing the # keyE 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 conferenceM Music-on-hold will be played when there is only one user in the
conferencex Close the conference when the last marked user exitsS Enter menu(user & administrator) when the * key is pressedP Always ask for a PIN even if it is specified
If a PIN argument is specified, the caller must enter that PIN in order toenter 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}]?103exten => 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 sectionand 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-reportingformats
The user-defined context contains the mailbox’s definition
[general] Section
Externnotify Supplies the full path and filename of an externalprogram to be executed when a voicemail is left ordelivered, or when a mailbox is checked
Externpass The path of the external program to be executed aftervoicemail’s password is changed
Silencethreshold When using the maxsilence setting, eliminate backgroundnoise by adjusting the silence detection’s threshold
Servermail Source e-mail addressMaxmsg Limits the number of messages in the voicemail folderMinmessage Eliminate a message shorter than the time in seconds
specified. The default is zero, which indicates no minimumtime
Format The voice messages’ format i.e. wav49, GSM and wavMaxgreet Limits a user’s recordable voicemail greetingSkipms 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 asan attachment
Delete After sending an e-mail, delete voicemail afternotification. Works with Attach, and can be used whiledefining the mailbox as:823 => 1234,office,[email protected],attach=yes|delete=1
Mailcmd Program used by Asterisk to send an e-mail, forexample:mailcmd=/usr/sbin/sendmail -v -t –f [email protected]
Maxsilence Indicates how many seconds of silence to allow beforeending the recording
[general] Section
Pbxskip Changes the subject line in a voicemail notificationmessage. Takes values yes or no. If yes, the Subject: linewill 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 voicemailnotification 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}\nsoyou 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 0to exit voicemail
Nextaftercmd If set to yes, the system will automatically play the nextmessage after deleting a voicemail message
[zonemessages] Section
Define time-zones for different users in the [zonemessages] section, andassign voicemail boxes to use the setting for one of these zones later.The syntax is:
Zonename= timezone|time_formatZonename is the name used to identify the zoneTimezone is the name of the system time zone as found in
/usr/share/zoneinfoTime_format specifies how the voicemail system should announce the
timesThe Time_format argument is composed of the following elements:Filename The filename of the sound file$(VAR) Variable substitutionA 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 YearI or I Hour, 12-hour clockH 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 MinutesP or p AM or PMQ Today, yesterdayR 24-hour time, including minutes
[zonemessages] Section
Examples:
12-hours Pacific Standard TimeSan-diego=America/Tijuana|’vm-received’Q’digits/at’IMP
24-hours Pacific Standard TimeSan-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 aredefined here:
Tz defines the time-zone setting as defined in the zonemessages section.For example:
123 => 2048, abc_user, [email protected],,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 invoicemail.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 playedb Cause the busy message to be playedg(#) 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 isspecified, 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=1234orMailbox=1234@context
FliteFlite (festival-lite) is a small, fast run-time synthesis engineasterisk-flite is a Flite text-to-speech module for the Asterisk open-
source PBX.
Flitecd /tmpwget http://asterisk-flite.sourceforge.net/extras/flite-1.3-sharedlibs.patchwget http://asterisk-flite.sourceforge.net/extras/flite-1.3-alsa_support.patchwget http://www.speech.cs.cmu.edu/flite/packed/flite-1.3/flite-1.3-release.tar.gzwget http://kent.dl.sourceforge.net/sourceforge/asterisk-flite/asterisk-flite-
0.5.tar.gztar -zxvf flite-1.3-release.tar.gzrm -f flite-1.3-release.tar.gzcd flite-1.3-releasepatch -p1 < ../flite-1.3-sharedlibs.patchpatch -p1 < ../flite-1.3-alsa_support.patch./configure --enable-sharedmakemake install
Flitecd ../tar -xzvf asterisk-flite-0.5.tar.gzrm -f asterisk-flite-0.5.tar.gzmv asterisk-flite-0.5 flite-1.3-release/cd flite-1.3-release/asterisk-flite-0.5makemake 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.ldconfigasterisk -rx 'restart now'asterisk -r
show application Flite
Fliteto 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, basedon 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 inthe queue.conf file
Sections of a queue.conf file: The general section supports onlypersistent members. If set to yes and if a member is added to thesystem via the AddQueueMember() application, the application willbe stored in AstDB and retained when restarting
PeriodicannouncePeriodicannounce and periodic-announce-frequency plays messages
such as “Thank you for holding ….” at regular intervals
WeightAssign a rank to the queue. If calls are waiting in multiple queues, then
the queue with the highest weight values will be presented to agentsfirst.
LeavewhenemptyTo remove callers from a queue when no agent is present, set this option
to yesWrapuptimeAllow a few seconds’ break to an agent after completing a callMemberdelayDelay between the time when a queue identifies a free agent and when
the call is connected to that agent
TimeoutrestartIf 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 channelsroundrobin Use the first available channel, then the second and so
on. Deprecated in 1.4; use rrmemory insteadleastrecent Ring the interface least recently called by this queuefewestcalls Ring the interface handling the fewest calls from this
queuerandom Ring randomlyrrmemory Round robin with memory. Remember where we left off
the last ring pass
TimeoutTimeout in seconds when calling an agentAnnouncePlay a file to an agent before the caller is connected. Useful for agents
who are logged into more than one queuemember => member_nameMembers of queueFor examplemember => agent/@1 a groupmember => agent/501 single agent
Monitor-formatRecord all completed calls. Possible values are wav, gsm, wav49Monitor-joinIf set to yes, it is an indication to merge the two files
Extensions.conf application
Queue()Format isQueue(queuename[|options[|URL][|announceoverride][|timeout]])queuename name of the context in queue.confOptions:t Allow the called user to transfer the callT Allow the calling user to transfer the callh 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
extensionr Ring instead of music-on-holdURL Send a URL to the called user if a channel supports this facility
AnnounceoverrideSet a sound file to override the one set in queues.confTimeoutMaximum 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 ispersistentagents. This option specifies whether the agent call-backlogins 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 answeringbefore an agent is logged off
ackall If an agent is logging with agentcallbacklogin, then anacknowledgement is required by pressing the # sign ifthis option is yes
Wrapuptime Time after the conversation is overMusiconhold Define the music-on-hold classUpdatecdr Change the source channel in cdr to
agent/agent- id to determine which agent generatedthe call
Group Group agents for easy managementgroup=groupnumber examplegroup =1agent => 888,888,user1
Custom-beep Accepts the filename as an argument. Notifiesan agent about an incoming call
Recordagentcalls Accept the argument yes or no.Specifies whether an agent’s calls shouldbe recorded or not
Recordformat Specifies the recording format (wav49, gsm or wav)Savecallsin Specifies the path to store recordingsUrlprefix String appended to the start of the text to be added to
the recording’s name
Creation of agentFormat isAgent => agentnumber, agent_password, nameAgent_number is an agent’s numberAgent_password is an agent’s passwordName 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 * keyFormat isAgentLogin([AgentNo][,options])The Option argument contains s, which causes the login to be silentExampleExten => 123,1,AgentLogin(42,s)AgentCallbackLogin()Format isAgentCallbackLogin([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 ofconnections:
• Analogue Connections• Digital Connections
Analogue Connections
FXO cards are used to connect Asterisk with PSTN using analoguephone lines and FXS cards are used to connect analogue phones toAsterisk
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 cardsOpenvox FXO and FXS Cards
Zaptel’s HardwareConfiguration
zaptel.conf is located in /etc and this file is used to configure hardware.For example:
fxsks=2loadzone=usdefaultzone=us
The card is FXO, therefore FXS with kewlstart signaling is defined forchannel 2. There can be any of the following three signals:
Loopstart Indicates on hook/off hook and ring/no ringKewlstart 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 asdefined in zonedata.c
Defaultzone The default zone is used if no zone is specified for achannel
Loading DriversUse 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. Tounload 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 thewrong signaling
2. Zttool is a diagnostic program which can also be used to determinethe hardware’s state
Zapata’s Hardware Configuration
After configuring zaptel.conf, the modules are loaded, but Asterisk isunaware 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 matchthe zaptel driver’s configurations. Can hold one of thefour values: fxs_ks, fxo_ks, pri_cpe or pri_net
ISDN PRI Switch Configuration
switchtype Type of PRI switchoverlapdial 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 likePLAR
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 indicationthreewaycalling If enabled, you can place a call on hold by pressing
a hook flash, whereupon you get a dialrecall toneand can make another call. The default is nothreewaycalling=yes
transfer This option is activated only whenthreewaycalling=yes. If threewaycalling=yes andtransfer=yes, then once you've placed a call on holdwith a hook flash, you can transfer that call toanother extension by dialing the extension andhanging up. The default is no
cancallforward If enabled, activate "call forwarding immediate" bydialling *72. Disable the call forwarding by dialing*73. The default is no
callreturn If enabled, dial *69 to have Asterisk read the callerID of the last person to call you
Callgroup A channel may belong to zero or more callgroups.Callgroups specify who will answer thisphone when it is ringing.If this channel is ringing,then any other channel whose pickupgroupsinclude one of this channel's callgroups may answerthe call by dialing *8#. Zap, SIP, Skinny andMGCP channels support this feature. group=1callgroup=1,2,3
Pickupgroup Pickupgroups specify whose phones you mayanswer. If another channel is ringing, and thischannel's pickupgroups include one of the ringingchannel's callgroups, then this channel may answerthe call by dialing *8#.group=1pickupgroup=3,4
Caller ID Options
Callerid Sets the Caller ID string forward to the recipient whencalls come in from this channel. This is normally used to setthe 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 causesAsterisk to look for Caller ID on incoming calls
Hidecallerid (Not for FXO trunk lines) For PRI channels, this will stopthe sending of Caller ID on outgoing calls. For FXShandsets, this will stop Asterisk from sending thischannel's Caller ID information to the called party whenyou make a call using this handset. FXS handset users mayenable or disable the sending of their Caller ID for thecurrent 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 cancellationduring a bridged TDM call.
Echotraining In some cases, the echo cancellerdoesn't train quickly enough andthere is an echo at the beginning ofthe call which then quickly fades out.Enabling echo training will causeAsterisk to briefly mute the channel,send an impulse, and use theimpulse’s response to pre-train theecho canceller so that it can start outwith a much more accurate conceptof the actual echo
Important
Context This specifies which context a call will start in:context=internal
Channel This keyword causes Asterisk to actually allocate achannel with the settings that have been specifiedearlier on in the file. Each channel definition willinherit all the options stated ahead of it in this file.Allocating a channel will not "clear" the settings, so anychannels defined later on in this file will inherit theoptions for this channel unless you override itssettings:
channel => 16channel => 2,3channel => 1-8
[trunkgroups]; define any trunk groups[channels]; hardware channels
; defaultusecallerid=yeshidecallerid=nocallwaiting=nothreewaycalling=yestransfer=yesechocancel=yesechotraining=yes; define channels
context=incoming ; Incoming calls go to [incoming] in extensions.confsignalling=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 RateInterface (PRI) and Basic Rate Interface (BRI)
PRI is the standard for connections to offices. It's based on a T1 line inthe US,and an E1 line in Europe. The T1 PRI consists of 24 channels, the E1PRI of 32.
The number of PRI channels varies from country to country.In North American and Japan it is 23B + 1D (23 64Kbps digitalchannels + 1 64Kbps signalling/control channel) on a T1 1.544 MbpsIn Europe and Australia it is 30B + 2D on an E1 2.048 MbpsChannel 0 is used for synchronization and channel 16 is used forsignalling.
E1 and T1
T1 ServicesT1 service can be provided as channelized or unchannelized. Thereare 24 channels in the channelized T1 version. Each channel can be atelephone call. T1 gives you 24 phone lines in place of the 23 that canbe accommodated with PRI. However, since there is no separatesignaling channel, the signaling information which indicates when aphone is on the hook or off the hook is carried within each channelby using or "robbing" the least significant bit. Unfortunately,channelized T1 does not provide any capability for ANI or caller IDdata. PRI service is required for that purpose.
Unchannelized T1 treats all 24 T1 line channels as one big combinedchannel for carrying Internet service, point-to-point data download orVoIP broadband phone. This service is intended to be handled bydigital routers, not PBX telephone systems. No dedicated phonechannels 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.3vPCI
TE410P - 4 span T1/E1/J1 Card for 3.3v PCITE406P - 4 span T1/E1/J1 Card with Hardware Echo Cancellation for 5v
PCITE405P - 4 span T1/E1/J1 Card for 5v PCITE210P - 2 span T1/E1/J1 Card for 3.3v PCITE205P - 2 span T1/E1/J1 Card for 5v PCITE110P - 1 span T1/E1/J1 Card for 3.3v or 5v PCI
SangomaA104A104
Configuring Digium’s Digital Hardware
Zaptel.conf configurations for Digium’s digital hardware are as follows:
SpanSpan format isSpan = (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 numberTiming How to synchronize the timing device0: Use as sync source. Send timing synchronization to
other end1: To use as primary sync source2: To set as secondary sync source and so forth
Line Build Out (LBO) A cable’s length between a zap card and asmartjack/telecom-provided modem. In case
of a long cable, use 0
Framing How to communicate with the hardware at theother end
For T1: Framing is d4 or esfFor E1: Framing is cas or ccs
Coding line encoding settingFor T1: Coding is ami or b8zsFor E1: Coding is ami or hdb3
Example:span=1,1,0,esf,b8zsFirst 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,crc4This 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 framingand hdb3 line encoding.crc-4 is error checking
Zaptel.confspan=1,1,0,esf,b8zs
bchan=1-23dchan=24
Zapata.conf
switchtype=nationalcontext=blahsignalling=pri_cpegroup=1channel => 1-23
Asterisk Real time
Asterisk Real time
Asterisk Real time allows the storage of users/peers data to be stored in adatabase
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 Asteriskdistribution’s add-ons section.
Installing MySQLcd /usr/srcwget http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.33.tar.gztar -zxvf mysql-5.0.33.tar.gzcd mysql-5.0.33groupadd mysqluseradd -g mysql mysql./configure –prefix = /usr/local/mysqlmakemake installScripts/mysql_install_dbchown -R root /usr/local/mysqlchown -R mysql /usr/local/mysql/varchgrp -R mysql /usr/local/mysql
cp Support-files/my-medium.cnf /etc/my.cnf
Installing MySQLStart MySQL:
/usr/local/mysql/bin/mysql_safe &
Create a symbolic link:
mkdir /var/lib/mysqlcd /var/lib/mysqlln -s /tmp/mysql.sock
Install the mysql-devel:
yum install mysql-devel
Installing Asterisk Real Time driverwget http://downloads.digium.com/pub/asterisk/old-releases/ asterisk-1.4.1x.tar.gztar -zxvf asterisk-addon-1.4.x.tar.gzcd 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 driverCompile and install:
make cleanmakemake install
Copy the configuration files to the /etc/asterisk directory:
cp cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.confcp res_mysql.conf.sample /etc/asterisk/res_mysql.conf
Configuring Databasemysql --user=root –password=password
CREATE DATABASE asteriskcdrdb;
GRANT ALLON asetriskcdrdb.*TO asteriskuser@localhostIDENTIFIED BY 'yourpassword';
Configuring DatabaseCreate 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 DatabaseCreate Asterisk Real Time Database:
CREATE DATABASE asteriskrealtime;
GRANT ALLON asetriskrealtime.*TO asteriskuser@localhostIDENTIFIED BY 'yourpassword';
Create Table for SIP Extensions:USE asteriskrealtime;CREATE TABLE sip_buddies ( ………………………………………………………..)
Connecting Asterisk CDRs With DatabaseEdit the configuration files. Edit cdr_mysql.conf
[global]hostname=127.0.0.1dbname=asteriskcdrdbtable=cdrpassword='your password'user=asteriskuser
Connecting Asterisk With DatabaseEdit res_mysql.conf
[general]dbhost = 127.0.0.1dbname = asteriskrealtimedbuser = asteriskuserdbpass = yourpassworddbport = 3306dbsock = /var/lib/mysql/mysql.sock
Connecting Asterisk With DatabaseEdit the /etc/asterisk/extconfig.conf as given below:
[settings]sipusers => mysql,asterisk,sip_buddiessippeers => mysql,asterisk,sip_buddiesextensions => mysql,asterisk,extensions