FON Script Interface

The FON Script API is provided free of charge, but not covered by Fonality Support. Fonality Support Engineers will not assist you with writing, modifying, or troubleshooting custom AGIs that you write or commission a 3rd party to write for you. Please do not contact Support for any reason relating to the information on this page (even questions) or AGIs in general.

 

 

Fon Script Interface Overview

The FON Script Interface allows software developers and system integrators to extend the functionality of their PBXtra CCE systems by allowing them to create customized extensions to the PBXtra system using a standardized API. This facility allows the creation of custom IVR applications that will impress your friends, and probably get you promoted ;-).

 

Example Application

One example of a FON Script application is a store locater. This program would prompt the caller to key in his zip code, and look up a list of stores in a cross reference table of a database. Once the correct store is identified the caller is then automatically connected with the correct store.

 

Prerequisite

You must have the PBXtra Call Center Edition of the Fonality software in order to use this feature. In CCE it will be shown in your call menu as "Run Script".

 

How To Configure Run Script

  1. Log into your PBXtra Admin Web Interface using your administrative username and password.

  2. Click on the AutoAnswer tab.

  3. Click on the call menu tab.

  4. Add a new Call Sequence named Run Script.

  5. Specify the path to the script in your /var/lib/asterisk/agi-bin/ directory.

Example:

my_script.agi

Example for a script listening on a port:

fon://ip.add.re.ss:port

Note: If you are running PBXtra Core version 1.2.14-fon-o or newer, you can also pass HTTP style arguments to the script like this:

my_script.agi?extension=${EXTEN}

You can look for them in your script using the environment variables.

 

Calling Your Script

If you have connected your FON Interface Script to your call menu, you can dial "0" from any of your extensions to reach your main menu, and subsequently reach the AGI for testing. You may also dial in from an external line.

 

Example Script

This example Perl script is available under the GNU GPLv2 or higher License. It demonstrates basic interaction with the PBXtra Core software from your server using the STDOUT file handle. It also shows how to get digit input from your callers.

 

Compatibility

The FON interface is 100% interface compatible with FastAGI. You can use any FastAGI development library you wish. The FON Interface for PBXtra Core improves efficiency over AGI, and allows for continued execution of your call menu if you ever have a problem with your FON Interface Script.

 

Languages

You may write FON Interface Scripts in any language you wish. They must be able to read input on STDIN, write output on STDOUT, and must be able to implement a simple request loop. See the sample script above for a working implementation. Technically speaking the FON Interface Script is a TCP/IP server program. Here are some other programming aids:

  • Erlang

ErlAst - A multi-threaded FastAGI server written in Erlang which lets you do your call control in Erlang.

  • Python

StarPy

  • Java

Asterisk-java FastAGI server allows you to write your AGI scripts in Java.

Jast Agi

  • Perl

Asterisk::FastAGI Allows you to easily write FastAGI scripts in Perl.

 

Programming Tips

Note that each call will occupy your FastAGI server for its duration until you set a context and priority sequence number and exit, allowing the call to continue to flow through your system as indicated. To support multiple callers at once you will want to employ a pre-fork multi-process server or a multi-threaded server to allow multiple calls at once. For Perl, consider the Net::Server::Prefork library.

If you decide to multi-thread, and you will have a high call volume, be careful. The default stack size is set to 2MB, and you may quickly soak up a lot of memory, and waste a lot of system resources allocating new threads. Consider using a thread pool so you can create all the threads you need at startup.

 

NOTE

For performance and stability reasons, please do not consider loading MySQL or any other database engine on the PBXtra server directly. If your application will use a database, then run it on a separate server and connect to it over a socket connection. 

Environment Variables

The following environment variables will be available to your FON Interface Script upon execution. Note that the values will be set dynamically based on the channel information on your inbound call.

  • accountcode =

  • callerid = "Fonality" <8773662548>

  • channel = Zap/1-1

  • context = icoming

  • dnid = unknown

  • enhanced = 0.0

  • extension = s

  • language = en

  • network = yes

  • priority = 1

  • rdnis = unknown

  • request = agi://127.0.0.1

  • type = Zap

  • uniqueid = 1096425459.28

 

FON Interface API Reference

ANSWER

Purpose Answer channel if not already in answer state.

 

Returns -1 on channel failure, or 0 if successful.


AUTOHANGUP <time>

Purpose Cause the channel to automatically hangup at <time> seconds in the future. If <time> is 0 then the auto-hangup feature is disabled on this channel.

 

Returns 0

 

Note

If the channel is hungup prior to <time> seconds, this setting has no effect.


CHANNEL STATUS [<channelname>]

Purpose Return the status of the specified channel. If no channel name is specified, return the status of the current channel.

 

Returns -1 There is no channel that matches the given <channelname> 0 Channel is down and available 1 Channel is down, but reserved 2 Channel is off hook 3 Digits (or equivalent) have been dialed 4 Line is ringing 5 Remote end is ringing 6 Line is up 7 Line is busy

 

Examples CHANNEL STATUS Return the status of the current channel.

 

CHANNEL STATUS Zap/9-1 Return the status of channel Zap/9-1

 

Note

The <channelname> to use is the same as the channel names reported by the Asterisk console 'show channels' command.


EXEC <application> <options>

Purpose Executes the specified Asterisk <application> with given <options>.

 

Returns Whatever the application returns, or -2 on failure to find the application.

The following list details all of the applications that can be invoked within the PBXtra Core software using the EXEC interface command.

 

AbsoluteTimeout: Set absolute maximum time of call

 

AddQueueMember: Dynamically adds queue members

 

ADSIProg: Load Asterisk ADSI Scripts into phone

 

AGI: Executes an AGI compliant application

 

AlarmReceiver: Provide support for receving alarm reports from a burglar or fire alarm panel

 

Answer: Answer a channel if ringing

 

AppendCDRUserField: Append to the CDR user field

 

Authenticate: Authenticate a user

 

BackGround: Play a file while awaiting extension

 

BackgroundDetect: Background a file with talk detect

 

Busy: Indicate the Busy condition

 

ChangeMonitor: Change monitoring filename of a channel

 

ChanInUse: Checks to see if channel is in use

 

ChanIsAvail: Check channel availability

 

ChanSpy: Listen to the audio of an active channel

 

CheckGroup: Check the channel count of a group against a limit

 

 

Congestion: Indicate the Congestion condition

 

ControlPlayback: Play a file with fast forward and rewind

 

Curl: Load an external URL

 

Cut: Splits a variable's contents using the specified delimiter

 

DateTime: Says a specified time in a custom format

 

DBdel: Delete a key from the database

 

DBdeltree: Delete a family or keytree from the database

 

DBget: Retrieve a value from the database

 

DBput: Store a value in the database

 

DeadAGI: Executes AGI on a hungup channel

 

Dial: Place a call and connect to the current channel

 

Dictate: Virtual Dictation Machine

 

DigitTimeout: Set maximum timeout between digits

 

Directory: Provide directory of voicemail extensions

 

DISA: DISA (Direct Inward System Access)

 

DumpChan: Dump Info About The Calling Channel

 

DUNDiLookup: Look up a number with DUNDi

 

EAGI: Executes an EAGI compliant application

 

Echo: Echo audio read back to the user

 

EndWhile: End A While Loop

 

EnumLookup: Lookup number in ENUM

 

Eval: Evaluates a string

 

Exec: Executes internal application

 

ExecIf: Conditional exec

 

ExecIfTime: Conditional application execution based on the current time

 

ExternalIVR: Interfaces with an external IVR application

 

Festival: Say text to the user

 

Flash: Flashes a Zap Trunk

 

FlushQueueStats: Flushes stats for specified queue

 

ForkCDR: Forks the Call Data Record

 

GetCPEID: Get ADSI CPE ID

 

GetGroupCount: Get the channel count of a group

 

GetGroupMatchCount: Get the channel count of all groups that match a pattern

 

Gosub: Jump to label, saving return address

 

GosubIf: 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

 

HasNewVoicemail: Conditionally branches to priority + 101 with the right options set

 

HasVoicemail: Conditionally branches to priority + 101 with the right options set

 

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

 

LookupBlacklist: Look up Caller*ID name/number from blacklist database

 

LookupCIDName: Look up CallerID Name from local database

 

Macro: Macro Implementation

 

MacroExit: Exit From Macro

 

MacroIf: Conditional Macro Implementation

 

MailboxExists: Check to see if Voicemail mailbox exists

 

Math: Performs Mathematical Functions

 

MD5: Calculate MD5 checksum

 

MD5Check: Check MD5 checksum

 

MeetMe: MeetMe conference bridge

 

MeetMeAdmin: MeetMe conference Administration

 

MeetMeCount: MeetMe participant count

 

Milliwatt: Generate a Constant 1000Hz tone at 0dbm (mu-law)

 

MixMonitor: Record a call and mix the audio during the recording

 

Monitor: Monitor a channel

 

MP3Player: Play an MP3 file or stream

 

MusicOnHold: Play Music On Hold indefinitely

 

NBScat: Play an NBS local stream

 

NoCDR: Tell Asterisk to not maintain a CDR for the current call

 

NoOp: Do Nothing

 

Page: Pages phones

 

Park: Park yourself

 

ParkAndAnnounce: Park and Announce

 

ParkedCall: Answer a parked call

 

PauseQueueMember: Pauses a queue member

 

Pickup: Directed Call Pickup

 

Playback: Play a file

 

PlayTones: Play a tone list

 

PrivacyManager: Require phone number to be entered, if no CallerID sent

 

Progress: Indicate progress

 

Queue: Queue a call for a call queue

 

Random: Conditionally branches, based upon a probability

 

Read: Read a variable

 

ReadFile: ReadFile(varname=file,length)

 

RealTime: Realtime Data Lookup

 

RealTimeUpdate: Realtime Data Rewrite

 

Record: Record to a file

 

RemoveQueueMember: Dynamically removes queue members

 

ResetCDR: Resets the Call Data Record

 

ResponseTimeout: Set maximum timeout awaiting response

 

 

Return: Return from gosub routine

 

Ringing: Indicate ringing tone

 

SayAlpha: 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

 

SendImage: Send an image file

 

SendText: Send a Text Message

 

SendURL: Send a URL

 

Set: Set channel variable(s) or function value(s)

 

SetAccount: Set the CDR Account Code

 

SetAMAFlags: Set the AMA Flags

 

SetCallerID: Set CallerID

 

SetCallerPres: Set CallerID Presentation

 

SetCDRUserField: Set the CDR user field

 

SetCIDName: Set CallerID Name

 

SetCIDNum: Set CallerID Number

 

SetGlobalVar: Set a global variable to a given value

 

SetGroup: Set the channel's group

 

SetLanguage: Set the channel's preferred language

 

SetMusicOnHold: Set default Music On Hold class

 

SetRDNIS: Set RDNIS Number

 

SetTransferCapability: Set ISDN Transfer Capability

 

SetVar: Set channel variable(s)

 

SIPAddHeader: Add a SIP header to the outbound call

 

SIPDtmfMode: Change the dtmfmode for a SIP call

 

SIPGetHeader: Get a SIP header from an incoming call

 

SMS: Communicates with SMS service centres and SMS capable analogue phones

 

SoftHangup: Soft Hangup Application

 

Sort: Sorts a list of keywords and values

 

StackPop: Remove one address from gosub stack

 

StartMusicOnHold: Play Music On Hold

 

StopMonitor: Stop monitoring a channel

 

StopMusicOnHold: Stop Playing Music On Hold

 

StopPlayTones: Stop playing a tone list

 

System: Execute a system command

 

TestClient: Execute Interface Test Client

 

TestServer: Execute Interface Test Server

 

Transfer: Transfer caller to remote extension

 

TrySystem: Try executing a system command

 

TXTCIDName: Lookup caller name from TXT record

 

UnpauseQueueMember: Unpauses a queue member

 

UserEvent: Send an arbitrary event to the manager interface

 

Verbose: Send arbitrary text to verbose output

 

VMAuthenticate: Authenticate with Voicemail passwords

 

VoiceMail: Leave a Voicemail message

 

VoiceMailMain: Check Voicemail messages

 

Wait: Waits for some time

 

WaitExten: Waits for an extension to be entered

 

WaitForRing: Wait for Ring Application

 

WaitForSilence: Waits for a specified amount of silence

 

WaitMusicOnHold: Wait, playing Music On Hold

 

While: Start A While Loop

 

Zapateller: Block telemarketers with SIT

 

ZapBarge: Barge in (monitor) Zap channel

 

ZapRAS: Executes Zaptel ISDN RAS application

 

ZapScan: Scan Zap channels to monitor calls


GET DATA <filename> [<timeout> [<max digits>]]

Purpose Plays the given file and receives DTMF data. This is similar to STREAM FILE, but this command can accept and return many DTMF digits, while STREAM FILE returns immediately after the first DTMF digit is detected.

 

Returns If the command ended due to timeout then the result is of the form

where <digits> will be zero or more ASCII characters depending on what the user pressed.

 

If the command ended because the maximum number of digits were entered then the result is of the form

and the number of digits returned will be equal to <max digits>.

 

In either case what you get are actual ASCII characters. For example if the user pressed the one key, the three key and then the star key, the result would be

This differs from other commands with return DTMF as numbers representing ASCII characters.

 

Notes

  • Don't give an extension with the filename.

  • Asterisk looks for the file to play in /var/lib/asterisk/sounds

  • If the user doesn't press any keys then the message plays, there is <timeout> milliseconds of silence then the command ends.

  • The user has the opportunity to press a key at any time during the message or the post-message silence. If the user presses a key while the message is playing, the message stops playing. When the first key is pressed a timer starts counting for <timeout> milliseconds. Every time the user presses another key the timer is restarted. The command ends when the counter goes to zero or the maximum number of digits is entered, whichever happens first.

  • If you don't specify a time out then a default timeout of 2000 is used following a pressed digit. If no digits are pressed then 6 seconds of silence follow the message.

  • If you want to specify <max digits> then you *must* specify a <timeout> as well.

  • If you don't specify <max digits> then the user can enter as many digits as they want.

  • Pressing the # key has the same effect as the timer running out: the command ends and any previously keyed digits are returned. A side effect of this is that there is no way to read a # key using this command.

 


GET VARIABLE <variablename>

Purpose Fetch the value of a variable.

 

Returns Returns 0 if the variable hasn't been set. Returns 1 followed by the value of the variable in parenthesis if it has been set.

 

Example SET VARIABLE Foo "This is a test" 200 result=1 GET VARIABLE Foo 200 result=1 (This is a test)


HANGUP [<channelname>]

Purpose Hangup the specified channel. If no channel name is given, hang up the current channel.

 

Returns If the hangup was successful then the result is 200 result=1

If no channel matches the <channelname> you specified then the result is 200 result=-1

 

Examples HANGUP Hangup the current channel.

 

HANGUP Zap/9-1 Hangup channel Zap/9-1

 

Notes

  • The <channelname> to use is the same as the channel names reported by the Asterisk console 'show channels' command.

  • With power comes responsibility. Hanging up channels other than your own isn't something that is done routinely. If you are not sure why you are doing so, then don't.


RECEIVE CHAR <timeout>

Purpose Receive a character of text from a connected channel. Waits up to <timeout> milliseconds for a character to arrive, or infinitely if <timeout> is zero.

 

Returns If a character is received, returns the ASCII value of the character as a decimal number. For example if the character 'A' is received the result would be

If the channel does not support text reception or if the no character arrives in <timeout> milliseconds then the result is

On error or failure the result is

 

Note: Most channels do not support the reception of text.


RECORD FILE <filename> <format> <escape digits> <timeout> [BEEP]

Purpose Record sound to a file until an acceptable DTMF digit is received or a specified amount of time has passed. Optionally the file BEEP is played before recording begins.

 

Returns The documentation in the code says on hangup the result is -1, however when I tried it the hangup result was

If an error occurs then the result is -1. This can happen, for example, if you ask for a non-existent format.

If the user presses an acceptable escape digit then the result is a number representing the ASCII digit pressed. For example if recording terminated because the user pressed the '2' key the result is

 

Example RECORD FILE foo gsm 123 5000 beep Record sound in gsm format to file 'foo.gsm'. Play a beep before starting to record. Stop recording if user presses '1', '2' or '3', after five seconds of recording, or if the user hangs up.

 

Notes

  • Don't put an extension on the filename; the filename extension will be created based on the <format> specified.

  • The file will be created in /var/lib/asterisk/sounds

  • <format> specifies what kind of file will be recorded. GSM is a commonly used format. To find out what other formats are supported start Asterisk with at a verbosity level of at least 2 (-vvc) and look for the messages that appear saying "== Registered file format <whatever>'. Most but not all registered formats can be used, for example, Asterisk can read but not write files in 'mp3' format.

  • If you don't want ANY digits to terminate recording then specify "" instead of a digit string. To change the above example so no digits terminate recording use RECORD FILE foo gsm "" 5000 beep

  • <timeout> is the maximum record time in milliseconds, or -1 for no timeout. When this document was written [Nov 2002] I was unable to get <timeout> to work; this command always kept recording until I pressed an escape digit or hung up, as if -1 had been specified for timeout. A patch to correct this has been submitted but has not yet shown up in the CVS tree.


SAY DIGITS <digit string> <escape digits>

Purpose Say the given digit string, returning early if any of the given DTMF escape digits are received on the channel. If no DTMF digits are to be received specify "" for <escape digits>.

 

Returns Zero if playback completes without a digit being received, or the ASCII numerical representation of the digit pressed, or -1 on error or hangup.

 

Example SAY DIGITS 123 78#

The digits 'one', 'two', 'three' are spoken. If the user presses the '7', '8' or '#' key the speaking stops and the command ends. If the user pressed no keys the result would be 200 result=0. If the user pressed the '#' key then the result would be 200 result=35.


SAY NUMBER <number> <escape digits>

Purpose Say the given number, returning early if any of the given DTMF escape digits are received on the channel. If no DTMF digits are to be accepted specify "" for <escape digits>.

 

Returns Zero if playback completes without a digit being received, or the ASCII numerical representation of the digit pressed, or -1 on error or hangup.

 

Example SAY NUMBER 123 789

The phrase 'one hundred twenty three' is spoken. If the user presses the '7', '8' or '9' key the speaking stops and the command ends. If the user pressed no keys the result would be 200 result=0. If the user pressed the '#' key then the result would be 200 result=35.

 


SEND IMAGE <image>

Purpose Send the specified image on a channel. The image name should not should not include the extension.

 

Returns Zero if the image is sent or if the channel does not support image transmission. Returns -1 only on error or hangup.

 

Notes

  • Asterisk looks for the image in /var/lib/asterisk/images

  • Most channels do not support the transmission of images.


SEND TEXT "<text to send>"

Purpose Send the given text to the connected channel.

 

Returns 0 if text is sent or if the channel does not support text transmission. Returns -1 only on error or hangup.

 

Example SEND TEXT "Hello world"

 

Note

  • Most channels do not support transmission of text.


SET CALLERID <caller ID specification>

Purpose Changes the caller ID of the current channel

 

Returns Always returns 200 result=1

 

Example SET CALLERID "John Smith"<1234567>

 

Notes

  • This command will let you take liberties with the <caller ID specification> but the format shown in the example above works well: the name enclosed in double quotes followed immediately by the number inside angle brackets. If there is no name then you can omit it.

  • If the name contains no spaces you can omit the double quotes around it.

  • The number must follow the name immediately; don't put a space between them.

  • The angle brackets around the number are necessary; if you omit them the number will be considered to be part of the name.


SET CONTEXT <new context>

Purpose Sets the context for continuation upon exiting the application.

 

Returns Always returns 200 result=0.

 

Example SET CONTEXT demo

 

Notes

  • Setting the context does NOT automatically reset the extension and the priority; if you want to start at the top of the new context you should set extension and priority yourself.

  • If you specify a non-existent context you receive no error indication (the result returned is still 'result=0') but you do get a warning message on the Asterisk console.


SET EXTENSION <new extension>

Purpose Set the extension to be used for continuation upon exiting the application.

 

Returns Always returns 200 result=0.

 

Example SET EXTENSION 23

 

Note

  • Setting the extension does NOT automatically reset the priority. If you want to start with the first priority of the extension you should set the priority yourself.

  • If you specify a non-existent extension you receive no error indication (the result returned is still 'result=0') but you do get a warning message on the Asterisk console.


SET PRIORITY <new priority number>

Purpose Set the priority to be used for continuation upon exiting the application.

 

Returns Always returns 200 result=0.

 

Example SET PRIORITY 5

 

Note

If you specify a non-existent priority you receive no error indication of any sort: the result returned is still 'result=0' and no warning is issued on the Asterisk console.


SET VARIABLE <variablename> <value>

Purpose Sets a variable to the specified value. The variables so created can later be used by later using ${<variablename>} in the dialplan.

 

Returns Always returns 200 result=1.

 

Example SET VARIABLE station zap/3

Creates a variable named 'station' with the value 'zap/3'.

 

Notes

  • Unlike most of Asterisk, variable names are case sensitive. The names 'Foo' and 'foo' refer to two separate and distinct variables.

  • If the value being assigned contains spaces then put it inside double quotes.

  • If you want double quotes inside the value then you have to escape them. For example to create a variable CID whose value is "John Doe"<555-1212> you could use: SET VARIABLE CID "\"John Doe \"<555-1212>

  • Be aware that the language you are using may eat the backslash before it gets passed to Asterisk; you may have to use two backslashes or otherwise tell the language that, yes, you really do want a backslash in the string you are sending.

  • These variables live in the channel Asterisk creates when you pickup a phone and as such they are both local and temporary. Variables created in one channel can not be accessed by another channel. When you hang up the phone, the channel is deleted and any variables in that channel are deleted as well.


STREAM FILE <filename> <escape digits>

Purpose Play the given audio file, allowing playback to be interrupted by a DTMF digit. This command is similar to the GET DATA command but this command returns after the first DTMF digit has been pressed while GET DATA can accumulated any number of digits before returning.

 

Returns If playback finished with no acceptable digit being pressed the result is zero. If an acceptable digit was pressed the result is the decimal representation of the pressed digit. If the channel was disconnected or an error occurred the result is -1.

 

Example STREAM FILE welcome #

Plays the file 'welcome'. If the user presses the '#' key the playing stops and the command returns 200 result=35

 

Note

  • Don't give an extension with the filename.

  • Asterisk looks for the file to play in /var/lib/asterisk/sounds

  • Use double quotes if the message should play completely. For example to play audio file 'welcome' without allowing interruption by digits use: STREAM FILE welcome ""


TDD MODE <setting>

Purpose Enable or disable TDD transmission/reception on the current channel.

 

Returns 1 if successful or 0 if the channel is not TDD capable.

 

Example TDD MODE on

 

Note

The argument <setting> can be 'on' or 'tdd' to enable tdd mode. It can also be 'mate' which apparently sets some unspecified tdd mode. If it is anything else ('off' for example) then tdd mode is disabled.


VERBOSE <message> [<level>]

Purpose Sends <message> to the Asterisk console via the 'verbose' message system.

 

Returns Always returns 1

 

Example VERBOSE Hello 3

Sends the message "Hello" to the console if the current Asterisk verbosity level is set to 3 or greater.

 

Notes

  • <level> is the verbosity level in the range 1 through 4.

  • If your message contains spaces, then enclose it in double quotes.

  • The Asterisk verbosity system works as follows. The Asterisk usbr gets to set the desired verbosity at startup time or later using the console 'set verbose' command. Messages are displayed on the console if their verbose level is less than or equal to desired verbosity set by the user. More important messages should have a low verbose level; less important messages should have a high verbose level.


WAIT FOR DIGIT <timeout>

Purpose Waits up to 'timeout' milliseconds for channel to receive a DTMF digit

 

Returns -1 on channel failure, 0 if no digit is received in timeout or the numerical value of the ascii of the digit received.

 

Note

  • Use -1 for the timeout value if you want the call to wait indefinitely.

  • Example WAIT FOR DIGIT 3000

  • This page has no content. Enrich Array by contributing.

Return to Documentation Home I Return to Sangoma Support