Asterisk – dialplans

Asterisk is a framework or toolkit designed for VOIP systems . It can support Enterprise communication systems like PBXs, call distributors, VoIP gateways , conference bridges etc . It is open source and free to use . It is developed in C and runs in linux .

Technically , Asterisk has protocol support for many telephony technologies and protocols such as SIP , H323 . It can connect old PSTN or copper line and VOIP .

Asterisk is a framework for building multi-protocol, real-time communications applications and solutions. Asterisk is to realtime voice and video applications as what Apache is to web applications

– asterisk.org

Combine the SIP channel, the PSTN interface channel and some Dialplan script and you have a gateway.
Change the Dialplan to drop calls into a ConfBridge session and you have a conference server.
Alter it once more to route calls into voice mailboxes and you have a voicemail server.
Tie it all together and you have an amazingly powerful phone system.

– asterisk.org

A repo containing Asterisk configuratiosn and common applications can be found at https://github.com/altanai/asteriskexamples

Quick Installation

goto /usr/src and download the preferred the version of asterisk code from
http://downloads.asterisk.org/pub/telephony/asterisk/

I am using the latest release candidate at the time writing this article asterisk-16.2.0-rc1-patch.tar.gz

Some external Dependencies apt-get install subversion

Then install the source dependencies

 sudo su
contrib/scripts/get_mp3_source.sh

This will install mp3 related programs such as


A addons/mp3
A addons/mp3/decode_ntom.c
A addons/mp3/interface.c
A addons/mp3/MPGLIB_README
A addons/mp3/common.c
A addons/mp3/huffman.h
A addons/mp3/tabinit.c
A addons/mp3/Makefile
A addons/mp3/README
A addons/mp3/decode_i386.c
A addons/mp3/dct64_i386.c
A addons/mp3/MPGLIB_TODO
A addons/mp3/mpg123.h
A addons/mp3/layer3.c
A addons/mp3/mpglib.h
Exported revision 202.

Actual dependencies will be installed via install_prereq script

contrib/scripts/install_prereq install

Output snippet

Run configure which will create scripts for next processes

 ./configure

Build third party scripts

make -j2

After build , to run the installation

make install

Asterisk PBX setup

make basic-pbx

The output should be

Installing basic-pbx config files…
Installing file configs/basic-pbx/README
Installing file configs/basic-pbx/asterisk.conf
Installing file configs/basic-pbx/cdr.conf
Installing file configs/basic-pbx/cdr_custom.conf
Installing file configs/basic-pbx/confbridge.conf
Installing file configs/basic-pbx/extensions.conf
Installing file configs/basic-pbx/indications.conf
Installing file configs/basic-pbx/logger.conf
Installing file configs/basic-pbx/modules.conf
Installing file configs/basic-pbx/musiconhold.conf
Installing file configs/basic-pbx/pjsip.conf
Installing file configs/basic-pbx/voicemail.conf
Updating asterisk.conf

Also run make config to make pbx configs

make config 

start asterisk

systemctl start asterisk

connect to asterisk tool for cli

asterisk -vvvr
Asterisk 16.2.0-rc1, Copyright (C) 1999 - 2018, 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 16.2.0-rc1 currently running on ip-172-31-45-26 (pid = 13388)
ip-172-31-45-26*CLI> 

Register sip phones with asterisk PBX and make / receive calls

To make calls among users, we need to configure channel driver with sip support . Using the sip protcol the phones within the enterprise will be able to send call signals out to one another. Open pjsip.conf

Take any endpoint from template , such as

;================================
;Laverne Roberts
;Software Engineer
[1113 (endpoint-internal-d70)
auth = 1113
aors = 1113
callerid = Laverne Roberts <1113>
[1113 (auth-userpass)
password = xxxxxxxx
username = xxxxxxxx
[1113 (aor-single-reg)
mailboxes = 1113@example

and set the values in sip softphone like zoiper , register with provided creds

registering sip phone zoiper with newly created asterisk PBX

If the registration creds used are not matching with the ones defines in pjsip.conf then REGISTER request failed message is displayed

Request 'REGISTER' from '' failed for 'x.x.x.x:18475' (callid: hp8iN6oWLRdER4zvEBdiUg..) - No matching endpoint found

On correct creds used the server prints traces such as

-- Added contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable
-- Removed contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' from AOR '1113' due to request
== Contact 1113/sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e has been deleted
== Endpoint 1113 is now Unreachable
-- Added contact 'sip:1113@x.x.x.x:18475;transport=UDP;rinstance=5af431512ae0af3a' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable

Alternatively one can also create new sip endpoints

Applications

Hello World

[internal_users]
exten => 6000,1,Answer()
exten => 6000,2,Verbose("---------------- Tring Tring -------")
exten => 6000,3,Wait(1)
exten => 6000,n,Playback(silence/1&hello-world)
exten => 6000,n,Hangup()

NoOP and printing channel variables

exten=>6124,1,Verbose(2,The channel name is ${CHANNEL})
same => n,Verbose(2,The unique id is ${UNIQUEID})
same => n,Verbose(2,The caller id is ${CALLERID(all)})
same => n,Verbose(2,The datetime is ${DATETIME})
same => n,Verbose(2,The timestamp is ${TIMESTAMP})
same => n,Verbose(2,The context is ${CONTEXT})
same => n,Verbose(2,The SYSTEMNAME is ${SYSTEMNAME})
same => n,Verbose(2,The PRIORITY is ${PRIORITY})
same => n,Verbose(2,The CHANNEL is ${CHANNEL})

settings varaibles and Say

exten=>6009,1,Verbose("------------ Set variable -------")
same => n,Set(COUNT=3)
same => n,SayNumber(${COUNT})
same => n,Set(${COUNT}=10)
same => n,SayNumber(${COUNT}) 

Simple Voicemail ( also need configuration on voicemail.conf)

exten => 1235,1,VoiceMail(1235,u)               

References :

Extra details

PBX cores settings 
Version:                     16.2.0-rc1
   Build Options:               BUILD_NATIVE, OPTIONAL_API
   Maximum calls:               Not set
   Maximum open file handles:   1024
   Root console verbosity:      5
   Current console verbosity:   5
   Debug level:                 0
   Maximum load average:        0.000000
   Minimum free memory:         0 MB
   Startup time:                10:27:35
   Last reload time:            10:27:35
   System:                      Linux/4.15.0-1021-aws built by root on x86_64 2019-02-11 11:48:29 UTC
   System name:                 
   Entity ID:                   0e:28:c0:44:39:5e
   PBX UUID:                    a2df96bb-6d1a-4f64-a953-cf02030e9851
   Default language:            en
   Language prefix:             Enabled
   User name and group:         /
   Executable includes:         Disabled
   Transcode via SLIN:          Enabled
   Transmit silence during rec: Disabled
   Generic PLC:                 Disabled
   Generic PLC on equal codecs: Disabled
   Min DTMF duration::          80
   Cache media frames:          Enabled
   RTP use dynamic payloads:    1
   RTP dynamic payload types:   35-63,96-127

Subsystems
   Manager (AMI):               Disabled
   Web Manager (AMI/HTTP):      Disabled
   Call data records:           Enabled
   Realtime Architecture (ARA): Disabled

 Directories
   Configuration file:          /etc/asterisk/asterisk.conf
   Configuration directory:     /etc/asterisk
   Module directory:            /usr/lib/asterisk/modules
   Spool directory:             /var/spool/asterisk
   Log directory:               /var/log/asterisk
   Run/Sockets directory:       /var/run/asterisk
   PID file:                    /var/run/asterisk/asterisk.pid
   VarLib directory:            /var/lib/asterisk
   Data directory:              /var/lib/asterisk
   ASTDB:                       /var/lib/asterisk/astdb
   IAX2 Keys directory:         /var/lib/asterisk/keys
   AGI Scripts directory:       /var/lib/asterisk/agi-bin
core show applications 

-= Registered Asterisk Applications =-
AddQueueMember: Dynamically adds queue members.
ADSIProg: Load Asterisk ADSI Scripts into phone
AELSub: Launch subroutine built with AEL
AgentLogin: Login an agent.
AgentRequest: Request an agent to connect with the channel.
AGI: Executes an AGI compliant application.
AlarmReceiver: Provide support for receiving alarm reports from a burglar or fire alarm panel.
AMD: Attempt to detect answering machines.
Answer: Answer a channel if ringing.
AttendedTransfer: Attended transfer to the extension provided and TRANSFER_CONTEXT
Authenticate: Authenticate a user
BackGround: Play an audio file while waiting for digits of an extension to go to.
BackgroundDetect: Background a file with talk detect.
BlindTransfer: Blind transfer channel(s) to the extension and context provided
Bridge: Bridge two channels.
BridgeAdd: Join a bridge that contains the specified channel.
BridgeWait: Put a call into the holding bridge.
Busy: Indicate the Busy condition.
CallCompletionCancel: Cancel call completion service
CallCompletionRequest: Request call completion service for previous call
CELGenUserEvent: Generates a CEL User Defined Event.
ChangeMonitor: Change monitoring filename of a channel.
ChanIsAvail: Check channel availability
ChannelRedirect: Redirects given channel to a dialplan target
ChanSpy: Listen to a channel, and optionally whisper into it.
ClearHash: Clear the keys from a specified hashname.
ConfBridge: Conference bridge application.
Congestion: Indicate the Congestion condition.
ContinueWhile: Restart a While loop.
ControlPlayback: Play a file with fast forward and rewind.
DAHDIRAS: Executes DAHDI ISDN RAS application.
DAHDIScan: Scan DAHDI channels to monitor calls.
DateTime: Says a specified time in a custom format.
DBdeltree: Delete a family or keytree from the asterisk database.
DeadAGI: Executes AGI on a hungup channel.
Dial: Attempt to connect to another device or endpoint and bridge the call.
Dictate: Virtual Dictation Machine.
Directory: Provide directory of voicemail extensions.
DISA: Direct Inward System Access.
DumpChan: Dump Info About The Calling Channel.
EAGI: Executes an EAGI compliant application.
Echo: Echo media, DTMF back to the calling party
EndWhile: End a while loop.
Exec: Executes dialplan application.
ExecIf: Executes dialplan application, conditionally.
ExecIfTime: Conditional application execution based on the current time.
ExitWhile: End a While loop.
ExtenSpy: Listen to a channel, and optionally whisper into it.
ExternalIVR: Interfaces with an external IVR application.
Festival: Say text to the user.
Flash: Flashes a DAHDI Trunk.
FollowMe: Find-Me/Follow-Me application.
ForkCDR: Forks the current Call Data Record for this channel.
GetCPEID: Get ADSI CPE ID.
Gosub: Jump to label, saving return address.
GosubIf: Conditionally jump to label, saving return address.
Goto: Jump to a particular priority, extension, or context.
GotoIf: Conditional goto.
GotoIfTime: Conditional Goto based on the current time.
Hangup: Hang up the calling channel.
HangupCauseClear: Clears hangup cause information from the channel that is available through HANGUPCAUSE.
IAX2Provision: Provision a calling IAXy with a given template.
ICES: Encode and stream using ‘ices’.
ImportVar: Import a variable from a channel into a new variable.
Incomplete: Returns AST_PBX_INCOMPLETE value.
Log: Send arbitrary text to a selected log level.
MailboxExists: Check to see if Voicemail mailbox exists.
MessageSend: Send a text message.
Milliwatt: Generate a Constant 1004Hz tone at 0dbm (mu-law).
MinivmAccMess: Record account specific messages.
MinivmDelete: Delete Mini-Voicemail voicemail messages.
MinivmGreet: Play Mini-Voicemail prompts.
MinivmMWI: Send Message Waiting Notification to subscriber(s) of mailbox.
MinivmNotify: Notify voicemail owner about new messages.
MinivmRecord: Receive Mini-Voicemail and forward via e-mail.
MixMonitor: Record a call and mix the audio during the recording. Use of StopMixMonitor is required to guarantee the audio file is available for processing during dialplan execution.
Monitor: Monitor a channel.
Morsecode: Plays morse code.
MP3Player: Play an MP3 file or M3U playlist file or stream.
MSet: Set channel variable(s) or function value(s).
MusicOnHold: Play Music On Hold indefinitely.
NBScat: Play an NBS local stream.
NoCDR: Tell Asterisk to not maintain a CDR for this channel.
NoOp: Do Nothing (No Operation).
Originate: Originate a call.
Page: Page series of phones
Park: Park yourself.
ParkAndAnnounce: Park and Announce.
ParkedCall: Retrieve a parked call.
PauseMonitor: Pause monitoring of a channel.
PauseQueueMember: Pauses a queue member.
Pickup: Directed extension call pickup.
PickupChan: Pickup a ringing channel.
Playback: Play a file.
PlayTones: Play a tone list.
PrivacyManager: Require phone number to be entered, if no CallerID sent
Proceeding: Indicate proceeding.
Progress: Indicate progress.
Queue: Queue a call for a call queue.
QueueLog: Writes to the queue_log file.
QueueUpdate: Writes to the queue_log file for OutBound calls and updates Realtime Data. Is used at h extension to be able to have all the parameters.
RaiseException: Handle an exceptional condition.
Read: Read a variable.
ReadExten: Read an extension into a variable.
ReceiveFAX: Receive a FAX and save as a TIFF/F file.
Record: Record to a file.
RemoveQueueMember: Dynamically removes queue members.
ResetCDR: Resets the Call Data Record.
RetryDial: Place a call, retrying on failure allowing an optional exit extension.
Return: Return from gosub routine.
Ringing: Indicate ringing tone.
SayAlpha: Say Alpha.
SayAlphaCase: Say Alpha.
SayDigits: Say Digits.
SayNumber: Say Number.
SayPhonetic: Say Phonetic.
SayUnixTime: Says a specified time in a custom format.
SendDTMF: Sends arbitrary DTMF digits
SendFAX: Sends a specified TIFF/F file as a FAX.
SendImage: Sends an image file.
SendText: Send a Text Message on a channel.
SendURL: Send a URL.
Set: Set channel variable or function value.
SetAMAFlags: Set the AMA Flags.
SMS: Communicates with SMS service centres and SMS capable analogue phones.
SoftHangup: Hangs up the requested channel.
SpeechActivateGrammar: Activate a grammar.
SpeechBackground: Play a sound file and wait for speech to be recognized.
SpeechCreate: Create a Speech Structure.
SpeechDeactivateGrammar: Deactivate a grammar.
SpeechDestroy: End speech recognition.
SpeechLoadGrammar: Load a grammar.
SpeechProcessingSound: Change background processing sound.
SpeechStart: Start recognizing voice in the audio stream.
SpeechUnloadGrammar: Unload a grammar.
StackPop: Remove one address from gosub stack.
StartMusicOnHold: Play Music On Hold.
Stasis: Invoke an external Stasis application.
StopMixMonitor: Stop recording a call through MixMonitor, and free the recording’s file handle.
StopMonitor: Stop monitoring a channel.
StopMusicOnHold: Stop playing Music On Hold.
StopPlayTones: Stop playing a tone list.
StreamEcho: Echo media, up to ‘N’ streams of a type, and DTMF back to the calling party
System: Execute a system command.
TestClient: Execute Interface Test Client.
TestServer: Execute Interface Test Server.
Transfer: Transfer caller to remote extension.
TryExec: Executes dialplan application, always returning.
TrySystem: Try executing a system command.
UnpauseMonitor: Unpause monitoring of a channel.
UnpauseQueueMember: Unpauses a queue member.
UserEvent: Send an arbitrary user-defined event to parties interested in a channel (AMI users and relevant res_stasis applications).
Verbose: Send arbitrary text to verbose output.
VMAuthenticate: Authenticate with Voicemail passwords.
VMSayName: Play the name of a voicemail user
VoiceMail: Leave a Voicemail message.
VoiceMailMain: Check Voicemail messages.
VoiceMailPlayMsg: Play a single voice mail msg from a mailbox by msg id.
Wait: Waits for some time.
WaitDigit: Waits for a digit to be entered.
WaitExten: Waits for an extension to be entered.
WaitForNoise: Waits for a specified amount of noise.
WaitForRing: Wait for Ring Application.
WaitForSilence: Waits for a specified amount of silence.
WaitUntil: Wait (sleep) until the current time is the given epoch.
While: Start a while loop.
Zapateller: Block telemarketers with SIT.
-= 167 Applications Registered =-