Page tree
Skip to end of metadata
Go to start of metadata

About

This page provides the documentation of the Lua FreeSWITCH API.

Docs Help Needed

session:execSome API aren't documented, so please feel free to improve the documentation and complete the API examples.

 Click here to expand ToC

API Events

These methods apply to generating events.

event:addBody

event:addBody helps in creating custom event.

 

You can add as much data to the body as you like, in this case 4 items are to be sent.

The result will be:

 Click here to expand the result

event:addHeader

event:delHeader

event:fire

event:getBody

event:getHeader

This is a generic API call.

Or, This can be used inside of a dialplan.lua to get certain information

event:getType

event:serialize

Use this to dump all available Headers to the console.

Or this to display them as an info message.

event:setPriority

event:fire (Sending an Event)

Using luarun to execute this code you can toggle the MWI on a registered phone on and off.

API Sessions

The following methods can be applied to existing sessions.

session:answer

Answer the session:

session:answered

Checks whether the session is flagged as answered (true anytime after the call has been answered)

session:bridged

Check to see if this session's channel is bridged to another channel.

session:check_hangup_hook

session:collectDigits

session:consoleLog

Log something to the FreeSWITCH logger from session. Arguments are log level and message.

session:destroy

Destroys the session and releases resources. This is done for you when your script ends, but if your script contains an infinite loop you can use this to terminate the session.

session:execute

session:execute(app, data)

NOTE: Callbacks (DTMF and friends) CAN NOT EXECUTE during an execute.

session:executeString

session:execute(api_string)

NOTE: Callbacks (DTMF and friends) CAN NOT EXECUTE during an execute.

session:flushDigits

session:flushEvents

session:get_uuid

session:get_uuid()

session:getDigits

Get digits:

  • getDigits has three arguments: max_digits, terminators, timeout
  • max_digits: maximum number of DTMF tones that will be collected
  • terminators: buffer of characters that will terminate the digit collection
  • timeout: timeout in milliseconds allowed for no input or after last digit is pressed and terminator isn't
  • interdigit: if no input is received timeout specified previously will be use, once input is received this becomes the new timeout. (optional default 0)
  • return: buffer containing collected digits
  • The method blocks until one of the exit criteria is met.

session:getState

Get the call state, i.e. "CS_EXECUTE". The call states are described in "switch_types.h".

session:getVariable

To get system variables such as ${hold_music}

session:hangup

You can hang up a session and provide an optional Hangup Cause Code Table.

 

or

session:hangupCause

You can find the hangup cause of an answered call and/or the reason an originated call did not complete. See Hangup Cause Code Table.

Example call retry based on hangup cause:

Here's a Lua example in code which retries a call depending on the hangup cause. It retries max_retries1 times and alternates between 2 different gateways:

NOTE: originate_str1 and originate_str21 are dial strings for 2 different gateways.

session:hangupState

session:insertFile

session:insertFile(<orig_file>, <file_to_insert>, <insertion_sample_point>)

Inserts one file into another. All three arguments are required. The third argument is in samples, and is the number of samples into orig_file that you want to insert file_to_insert. The resulting file will be written at the sample rate of the session, and will replace orig_file.

Because the position is given in samples, you'll need to know the sample rate of the file to properly calculate how many samples are X seconds into the file. For example, to insert a file two seconds into a .wav file that has a sample rate of 8000Hz, you would use 16000 for the insertion_sample_point argument.

Note that this method requires an active channel with a valid session object, as it needs the sample rate and the codec info from the session.

Examples:

session:mediaReady

session:originate

session:originate is deprecated, use the following construct instead:

new_session = freeswitch.Session("sofia/gateway/gatewayname/18001234567", session);

The code below is here for the sake of history only; please do not use it going forward.

 


dest - quoted dialplan destination. For example: "sofia/internal/1000@10.0.0.1" or "sofia/gateway/my_sip_provider/my_dest_number"

 

timeout - origination timeout in seconds

Note: session.originate expects at least 2 arguments.

session:playAndGetDigits

Plays a file and collects DTMF digits. Digits are matched against a regular expression. Non-matching digits or a timeout can trigger the playing of an audio file containing an error message. Optional arguments allow you to transfer to an extension on failure, and store the entered digits into a channel variable.

Syntax

digits = session:playAndGetDigits (
          min_digits, max_digits, max_attempts, timeout, terminators,
          prompt_audio_files, input_error_audio_files,
          digit_regex, variable_name, digit_timeout,
          transfer_on_failure)

Arguments

 

min_digitsThe minimum number of digits required.
max_digitsThe maximum number of digits allowed.
max_attemptsThe number of times this function waits for digits and replays the prompt_audio_file when digits do not arrive.
timeoutThe time (in milliseconds) to wait for a digit.
terminatorsA string containing a list of digits that cause this function to terminate.
prompt_audio_fileThe initial audio file to play. Playback stops if digits arrive while playing. This file is replayed after each timeout, up to max_attempts.
input_error_audio_fileThe audio file to play when a digit not matching the digit_regex is received. Received digits are discarded while this file plays. Specify an empty string if this feature is not used.
digit_regexThe regular expression used to validate received digits.
variable_name(Optional) The channel variable used to store the received digits.
digit_timeout(Optional) The inter-digit timeout (in milliseconds). When provided, resets the timeout clock after each digit is entered, thus giving users with limited mobility the ability to slowly enter digits without causing a timeout. If not specified, digit_timeout is set to timeout.
transfer_on_failure(Optional) In the event of a failure, this function will transfer the session to an extension in the dialplan. The syntax is "extension-name [dialplan-id [context]]".

 

Discussion

  • This function returns an empty string when all timeouts and retry counts are exhausted.
  • When the maximum number of allowable digits is reached, the function returns immediately, even if a terminator was not entered.
  • If the user forgets to press one of the terminators, but has made a correct entry, the digits are returned after the next timeout.
  • The session has to be answered before any digits can be processed. If you do not answer the call you, the audio will still play, but no digits will be collected.

Examples

This example causes FreeSWITCH to play prompt.wav and listen for between 2 and 5 digits, ending with the # key. If the user enters nothing (or something other than a digit, like the * key) error.wav is played, and the process is repeated another two times.

This time, we require only one digit, and it must be 1, 3 or 4. If the user does not comply after three attempts, they are transferred to the operator extension in the "default" XML dial plan.

If the user presses a correct key, that digit is returned to the caller, and the "digits_received" channel variable is set to the same value.

Reminder: If you need to match the * key in the regular expression, you will have to quote it twice:

session:preAnswer

Pre answer the session:

session:read

Play a file and get digits.

session:read has 5 arguments: <min digits> <max digits> <file to play> <inter-digit timeout> <terminators>

This shows how you can figure out which terminator was pressed, if any:

session:ready

- checks whether the session is still active (true anytime between call starts and hangup)
- also session:ready will return false if the call is being transferred. Bottom line is you should always be checking session:ready on any loops and periodicly throughout your script and exit asap if it returns false.

See #session:hangupCause for more detail on if NOT ready.

session:recordFile

syntax is ended_by_silence = session:recordFile(file_name, max_len_secs, silence_threshold, silence_secs)

silence_secs is the amount of silence to tolerate before ending the recording.
ended_by_silence is 0 if recording was ended by something else, eg an input callback getting dtmfs

session:sayPhrase

Play a speech phrase macro.

session:sayPhrase(macro_name [,macro_data] [,language]);
  • macro_name - (string) The name of the say macro to speak.
  • macro_data - (string) Optional. Data to pass to the say macro.
  • language - (string) Optional. Language to speak macro in (ie. "en" or "fr"). Defaults to "en".

To capture events or DTMF, use it in combination with session:setInputCallback

Example:

When used with setInputCallback, the return values and meanings are as follows:

  • true or "true" - Causes prompts to continue speaking.
  • Any other string value interrupts the prompt.

session:sendEvent

session:setAutoHangup

By default, lua script hangs up when it is done executing. If you need to run the next action in your dialplan after the lua script, you will need to setAutoHangup to false. The default value is true.

session:setHangupHook

In your lua code, you can use setHangupHook to define the function to call when the session hangs up.

Other possibilities to exit the script (and throwing an error)

return "exit";
or
return "die";
or
s:destroy("error message");

session:setInputCallback

When used outside of streaming a file to a channel the return values "true" or "undefined" are accepted as true(which continues the audio stream I believe), anything else will be evaluated as false(which would stop the stream).

TODO: Additional return values can be located in the file ./src/switch_ivr.c around line 3359 with the option for "speed". Could not find out every option effect yet.

Return value effect.

Notice: Every return values are should be STRING.

Return valueEffect(When streaming audio)
"speed"Unknown
"volume"Unknown
"pause"Stop audio util get the next input. After get the another input, then it play continally.
"stop"Unkown
"truncate"Unkown
"restart"Unkown
"seek"Unkown
"true"Wait until the audio finish.

"false"

Stop the audio, immediately.
None/NULLDon't return None/NULL. It makes type error problem. Especially python.

 

session:setVariable

Set a variable on a session:

session:sleep

  • This will allow callbacks to DTMF to occur and session:execute("sleep", "5000") won't.

session:speak

session:say

Plays pre-recorded sound files for things like numbers, dates, currency, etc. Refer to Misc. Dialplan Tools say for info about the say application.

Arguments: <lang><say_type><say_method>

Example:

session:streamFile

Stream a file endless to the session

Stream a file endless to the session starting at sample_count?

session:transfer

Transfer the current session. The arguments are extensions, dialplan and context.

execution of your lua script will immediately stop, make sure you set session:setAutoHangup(false) if you don't want your call to disconnect


If instead you do session:execute("transfer", "3000 XML default") then the execution of the LUA script continues even though the call is mostly out of your control now, and bridges most likely will fail.

session:unsetInputCallback

session:waitForAnswer

Non-Session API

These methods are generic in that they do not apply to a session or an event. For example, printing data to the FreeSWITCH console is neither event- nor session-specific.

freeswitch.API

When calling a Lua script from the dialplan you always have the session object. However, Lua can also be called from the CLI. In either case, it is possible to execute API commands from within Lua by creating an API object:

In the above snippet, the Lua variable reply would receive the version number from FreeSWITCH.

You can do more intricate things as well, like this:

The Lua variable sofia would contain the total output of the sofia status command.

freeswitch.bridge

freeswitch.consoleCleanLog

freeswitch.consoleLog

Log something to the freeswitch logger. Arguments are loglevel, message.

freeswitch.Dbh

Get an ODBC or core (sqlite) database handle from FreeSWITCH and perform an SQL query through it.

Advantage of this method is that it makes use of connection pooling provided by FreeSWITCH which gives a nice increase in speed when compared to creating a new TCP connection for each LuaSQL env:connect().

It works as follows:

  • freeswitch.Dbh(odbc://my_db:uname:passwd) gets an ODBC db handle from the pool.
  • freeswitch.Dbh("sqlite://my_db") gets a core db (sqlite) db handle from the pool (this automatically creates the db if it didn't exist yet).
  • dbh:connected() checks if the handle is still connected to the database, returns true if connected, false otherwise.
  • dbh:test_reactive("test_sql", "drop_sql", "reactive_sql") performs test_sql and if it fails performs drop_sql and reactive_sql (handy for initial table creation purposes)
  • dbh:query("query", function()) takes the query as a string and an optional Lua callback function that is called on each row returned by the db.
    • The callback function is passed a table representation of the current row for each iteration of the loop. 
      Syntax of each row is: { ["column_name_1"] = "value_1", ["column_name_2"] = "value_2" }.
    • If you (optionally) return a number other than 0 from the callback-function, you'll break the loop.
  • dbh:affected_rows() returns the number of rows affected by the last run INSERT, DELETE or UPDATE on the handle. It does not respond to SELECT operations.
  • dbh:release() (optional) releases the handle back to the pool so it can be re-used by another thread. This is also automatically done when the dbh goes out of scope and is garbage collected (for example when your script returns). Useful for long-running scripts to release the connection sooner.

Take a look here for some examples.

freeswitch.email

Send an email with optional (converted) attachment.

Note that for this to work you have to have an MTA installed on your server, you also need to have 'mailer-app' configured in your switch.conf.xml.

You can use freeswitch.email as follows:

freeswitch.email(to, from, headers, body, file, convert_cmd, convert_ext)
  • to (mandatory) a valid email address
  • from (mandatory) a valid email address
  • headers (mandatory) for example "subject: you've got mail!\n"
  • body (optional) your regular mail body
  • file (optional) a file to attach to your mail
  • convert_cmd (optional) convert file to a different format before sending
  • convert_ext (optional) to replace the file's extension

Example:

then the following system command will be executed before attaching "message.mp3" to the mail and send it on its way:

mp3enc message.wav message.mp3

freeswitch.Event

This is firing a custom event my::event.

freeswitch.EventConsumer

Consumes events from FreeSWITCH.

Usage (single event subscription):

Usage (multiple specific event subscriptions):

Examples:

freeswitch.getGlobalVariable

Retrieves a global variable

freeswitch.IVRMenu

When using SAY, 3 additional variables have to be set or you will get the following error:

> [ERR] mod_lua.cpp:182 Error in IVRMenu expected 16..16 args, got 13 stack traceback:
> [C]: in function 'IVRMenu'
> /usr/local/freeswitch/scripts/ivr.lua:19: in main chunk

These variables are:

    ["tts_engine"]          = "flite",
    ["tts_voice"]           = "rms",
    ["max_timeouts"]        = "2"

freeswitch.msleep

Tells script to sleep for a specified number of milliseconds.
NOTE: Do not use this on a session-based script or bad things will happen.

freeswitch.Session

Create a new session.

Create a new session with execute_on_answer variable set.

stream:write

API commands

You can write FreeSWITCH API commands *in Lua* by using the lua FreeSWITCH API command to run a script and pass the arguments in, then whatever you write with the stream object is what you get as a reply to that command. For example, given a script in the scripts directory called hello.lua with the following content:

Running 'lua hello.lua' from the FreeSWITCH console would return back "hello world".

Or calling it from the dialplan like so:

Would set the channel variable "foo" to "hello world".

Web page interaction (via mod_xml_rpc)


Example: Call Control

Special Case: env object

When lua is called as the hangup hook there will be a special env object that contains all the channel variables from the channel that just disconnected.

Add an extension to test this feature:

 

Then add freeswitch/scripts/hook-test.lua:

Watch the FS console and dial 1234 and then hangup. You'll see all your channel variables!

Known issues

  • lua ssl module - If you are using lua ssl module it might crash freeswitch, for me using it in Lua scripts was no issue, but if I was using lua ssl in hangup hook it was crashing freeswitch constantly. Comment from Mike: "Openssl has a global initializer and no way to keep it from only being run once. We run that in FreeSWITCH, then the luassl module re-runs it (corrupting the global openssl structures). There is no scoped way to keep it from doing that without writing a custom ssl lua wrapper specifically for FreeSWITCH. Writing this is a possibility but not something we plan on doing."

See also