UAS API - Quickstart Sample Application

  • Filename:

    samples/quickstart.py

    Description:

    An inbound application that is provided as the default target application for the inbound developer service. It rings the call for 2 seconds, answers the call, then reads out the decoded pincode and username from the called address before hanging up.

    The main() function of the Python code is executed by the UAS when an incoming call is detected. This function receives a number of parameters.

    Parameter NameDescription
    channel Provides access to the call and media control API
    application_instance_id provides a unique ID for this instance of the application
    file_man provides access to the file management API
    my_log provides a reference to the UAS logger
    application_parameters provides access to the parameter string set on the inbound service page

    The application extracts the information that it wants to say from the channel.Details.call_to parameter and uses the function channel.FilePlayer.say() to speak it using Text-To-Speech technology. The caller may hangup at any time, in which case most of the channel functions will raise a Hangup exception. Applications should always catch any exceptions in a try and except block, just as this sample code does. At the end of the application, the logger is used to write a completed message.

    Code:

    """
        An inbound application that is provided as the default target application for the inbound developer service. 
        It rings the call for 2 seconds, answers the call, then reads out the decoded pincode and username from the called address before hanging up. 
    """
    
    __uas_identify__ = "application"
    __uas_version__ = "1.0b3"
    
    import sys, os
    from prosody.uas import Hangup, Error
    
    SIP_PREFIX = "sip:"
    PINCODE_PREFIX = "--"
    PINCODE_LEN = 8
    
    # Speak the pin code as separate digits.
    def get_tts_str_from_pincode(pincode):
        ttsstr = ', '.join(list(pincode))
        return ttsstr
    
    # Get suitable string for TTS based on SIP username in supplied call_to.
    # The SIP username must start with "sip:".
    # If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
    def get_tts_str_from_username(my_log, log_pref, call_to):
        # check we have a sane call_to
        splat = call_to.split("@")
        if len(splat) != 2:
            return "an unknown SIP username"
        if not splat[0].startswith(SIP_PREFIX):
            return "an unknown SIP username"
        username = splat[0][len(SIP_PREFIX):]
        # if we have a pin code, try to speak it nicely
        if username.startswith(PINCODE_PREFIX):
            pincode = username[len(PINCODE_PREFIX):]
            try:
                int(pincode)
            except ValueError:
                pincode = ""
            if len(pincode) == PINCODE_LEN:
                my_log.info("{0} username [{1}] pincode [{2}]".format(log_pref, username, pincode))
                tts_str = get_tts_str_from_pincode(pincode)
                return "user pin code{0}".format(tts_str)
        # otherwise, just return the username
        my_log.info("{0} username [{1}]".format(log_pref, username))
        return "SIP username {0}".format(username)
    
    def main(channel, application_instance_id, file_man, my_log, application_parameters):
        return_code = 0
        log_pref = "quickstart:"
        call_to = channel.Details.call_to
        my_log.info("{0} started with call_to [{1}]".format(log_pref, call_to))
        tts_str = get_tts_str_from_username(my_log, log_pref, call_to)
        try:
            channel.ring(2)
            channel.answer()
            channel.FilePlayer.say("Hello, this is the quick start application for {0}. Have a good day. Goodbye.".format(tts_str))
            channel.hang_up()
            
        except Hangup as exc:
            my_log.info("{0} completed with Hangup".format(log_pref))
    
        except Error as exc:
            my_log.exception("{0} completed with Error exception! {1}".format(log_pref, exc))
            return_code = -101
    
        except Exception as exc:
            my_log.exception("{0} completed with exception! {1}".format(log_pref, exc))
            return_code = -102
    
        my_log.info("{0} completed".format(log_pref))
        return return_code
    
  • Filename:

    Samples\C#\QuickStart\QuickStart.cs

    Description:

    The C# application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername method to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. this.Trace.TraceInfo("some log info").

    Code:

    using System;
    using System.Threading;
    using AMSClassLibrary;
    using UASAppAPI;
    
    // A simple inbound application that rings the call for 4 seconds, answers the call, then 
    // reads out the decoded pincode and username from the callTo parameter before hanging up.
    namespace QuickStart
    {
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        public class QuickStart : UASInboundApplication
        {
            // Possible return codes
            enum ReturnCode
            {
                // Success Codes:
                Success = 0,
                // ... any positive integer
    
                // Fail Codes:
                // -1 to -99 reserved
                ExceptionThrown = -100
            }
    
            const string sipPrefix = "sip:";
            const string pincodePrefix = "--";
            const int pinCodeLength = 8;
    
            // This is the entry point for the application
            public override int Run(UASCallChannel channel,
                                    string applicationParameters)
            {
                this.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters);
                ReturnCode reply = ReturnCode.Success;
    
                try
                {
                    string callTo = channel.CallDetails.CallTo;
                    this.Trace.TraceInfo("Call started with callTo [{0}]", callTo);
    
                    // Decode the pincode/username from the callTo
                    string tts = GetTtsFromUsername(callTo);
                    channel.Ring(4);
                    channel.Answer();
    
                    // Say it back to caller
                    channel.FilePlayer.Say(
                        "Hello, this is the quick start application for {0}. Have a good day. Goodbye.", tts);
                }
                catch (Exception e)
                {
                    this.Trace.TraceError("Exception thrown {0}", e.Message);
                    reply = ReturnCode.ExceptionThrown;
                }
                finally
                {
                    channel.HangUp();
                }
    
                this.Trace.TraceInfo("Completed with return code {0}", reply);
                return (int)reply;
            }
    
            // Convert the pin code to comma-separated digits.
            private string GetTtsFromPinCode(string pinCode)
            {
                string tts = "";
                foreach (char c in pinCode)
                {
                    if (tts.Length > 0) {
                        tts += ", ";
                    }
                    tts += c;
                }
                return tts;
            }
    
            // Get suitable string for TTS based on SIP username in supplied callTo.
            // The SIP username must start with "sip:".
            // If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            private string GetTtsFromUsername(string callTo)
            {
                // check we have a sane callTo
                string[] splits = callTo.Split(new char[] {'@'});
                if (splits.Length != 2)
                {
                    return "an invalid SIP username";
                }
                if (!splits[0].StartsWith(sipPrefix))
                {
                    return "an invalid SIP username";
                }
    
                // Remove the Sip:
                string username = splits[0].Substring(sipPrefix.Length);
                
                // If we have a pin code, try to say it nicely.
                if (username.StartsWith(pincodePrefix))
                {
                    string pinCode = username.Substring(pincodePrefix.Length); 
    
                    // Is it the right length
                    if (pinCode.Length != pinCodeLength)
                    {
                        return "a pin code that is not of length " + pinCodeLength;
                    }
    
                    try
                    {
                        int pinCodeValue = Convert.ToInt32(pinCode);
                    }
                    catch (Exception)
                    {
                        return "an invalid pin code";
                    }
    
                    this.Trace.TraceInfo("Username [{0}] pincode [{1}]", username, pinCode);
                    return "user pin code " + GetTtsFromPinCode(pinCode);
                }
    
                // Otherwise, just return the username
                this.Trace.TraceInfo("Username [{0}]", username);
                return "SIP username " + username;
            }
        }
    }
    
  • Filename:

    Samples\VB\QuickStart\QuickStart.vb

    Description:

    The Visual Basic application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername method to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. Me.Trace.TraceInfo("some log info").

    Code:

    Imports AMSClassLibrary
    Imports UASAppAPI
    
    ' A simple inbound application that is provided as the default Developer Service Target Entry.
    ' It rings the call for 4 seconds, answers the call, then reads out the decoded pincode 
    ' and username from the callTo parameter before hanging up.
    Namespace QuickStart
    
        ' The application class.
        ' This must have the same name as the assembly and must inherit from either 
        ' UASInboundApplication or UASOutboundApplication.
        ' It must override the Run method.
        Public Class QuickStart
            Inherits UASInboundApplication
    
            ' Possible return codes
            Enum ReturnCode
                ' Success Codes:
                Success = 0
                ' ... any positive integer
    
                ' Fail Codes:
                ' -1 to -99 reserved
                ExceptionThrown = -100
            End Enum
    
            ' Some features of the developer pin code
            Const sipPrefix = "sip:"
            Const pincodePrefix = "--"
            Const pinCodeLength = 8
    
            ' This is the entry point for the application
            Overrides Function Run(ByVal channel As UASCallChannel, _
                                   ByVal applicationParameters As String) _
                                   As Integer
    
                Me.Trace.TraceInfo("Start - appParms [{0}]", applicationParameters)
                Dim reply As ReturnCode = ReturnCode.Success
    
                Try
                    Dim callTo = channel.CallDetails.CallTo
                    Me.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                    ' Decode the pincode/username from the callTo
                    Dim tts = GetTtsFromUsername(callTo)
                    channel.Ring(4)
                    channel.Answer()
    
                    ' Say it back to caller
                    channel.FilePlayer.Say( _
                        "Hello, this is the quick start application for {0}. Have a good day. Goodbye.", tts)
    
                Catch ex As Exception
                    Me.Trace.TraceError("Exception thrown {0}", ex.Message)
                    reply = ReturnCode.ExceptionThrown
                Finally
                    channel.HangUp()
                End Try
    
                Me.Trace.TraceInfo("Completed with return code {0}", reply)
                Return reply
    
            End Function
    
            ' Convert the pin code to comma-separated digits.
            Private Function GetTtsFromPinCode(ByVal pinCode As String) As String
                Dim tts = ""
                For Each c In pinCode
                    If tts.Length > 0 Then
                        tts += ", "
                    End If
                    tts += c
                Next
                Return tts
            End Function
    
            ' Get suitable string for TTS based on SIP username in supplied callTo.
            ' The SIP username must start with "sip:".
            ' If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            Private Function GetTtsFromUsername(ByVal callTo As String) As String
                ' check we have a sane callTo
                Dim splits = callTo.Split("@")
                If splits.Length <> 2 Then
                    Return "an invalid SIP username"
                End If
    
                If Not splits(0).StartsWith(sipPrefix) Then
                    Return "an invalid SIP username"
                End If
    
                ' Remove the Sip:
                Dim username = splits(0).Substring(sipPrefix.Length)
    
                ' If we have a pin code, try to speak it nicely
                If username.StartsWith(pincodePrefix) Then
                    Dim pinCode = username.Substring(pincodePrefix.Length)
    
                    ' Is it the right length
                    If pinCode.Length <> pinCodeLength Then
                        Return "a pin code that is not of length " + pinCodeLength
                    End If
    
                    Try
                        Dim pinCodeValue = Convert.ToInt32(pinCode)
                    Catch
                        Return "an invalid pin code"
                    End Try
    
                    Me.Trace.TraceInfo("Username [{0}] pincode [{1}]", username, pinCode)
                    Return "user pin code " + GetTtsFromPinCode(pinCode)
                End If
    
                ' Otherwise, just return the username
                Me.Trace.TraceInfo("Username [{0}]", username)
                Return "SIP username " + username
            End Function
        End Class
    
    End Namespace
  • Filename:

    Samples\F#\QuickStart\QuickStart.fs

    Description:

    The application code is initiated via the Run() method that is called by the UAS. Arguments supplied to this method are the UASCallChannel with which SIP and PSTN calls are controlled and an applicationParameters string. This string is specified in the Inbound Service that was invoked and resulted in this application being run.

    The UASCallChannel class contains a property CallDetails which provides information associated with a call. The CallTo property is the destination address of the inbound call. This is manipulated by the GetTtsFromUsername() member function to decode the pincode/username.

    We simulate the phone ringing for four seconds with channel.Ring(4) and then answer the call with channel.Answer(). channel.FilePlayer provides a way of playing wav files and also to convert text into audio speach which can then be played to a call. The Say() method uses Text-To-Speech (TTS) to produce audio data.

    The caller may hangup at any time, in which case the channel.State property will go to Idle. Notice that we can use the Trace property of the application's base class to log application information e.g. obj.Trace.TraceInfo("some log info").

    Code:

    // A simple inbound application that is provided as the default Developer Service Target Entry.
    // It rings the call for 4 seconds, answers the call, then reads out the decoded pin code 
    // and username from the callTo parameter before hanging up.
    namespace QuickStart
    
        open System
        open System.Threading
        open AMSClassLibrary
        open UASAppAPI
    
        // Possible return codes
        type ReturnCode =
            // Success Codes:
            | Success = 0
            // ... any positive integer
    
            // Fail Codes:
            // -1 to -99 reserved
            | ExceptionThrown = -100
    
        // The application class.
        // This must have the same name as the assembly and must inherit from either 
        // UASInboundApplication or UASOutboundApplication.
        // It must override the Run method.
        type QuickStart() = 
            inherit UASInboundApplication()
    
            let sipPrefix = "sip:"
            let pincodePrefix = "--"
            let pinCodeLength = 8
    
            // This is the entry point for the application
            override obj.Run(channel:UASCallChannel, applicationParameters:string) : int = 
                
                let mutable reply = ReturnCode.Success
    
                try
                    try
                        let callTo = channel.CallDetails.CallTo
                        obj.Trace.TraceInfo("Call started with callTo [{0}]", callTo)
    
                        // Decode the pin code/username from the callTo
                        let tts : string = obj.GetTtsFromUsername(callTo)
    
                        channel.Ring(4) |> ignore
                        channel.Answer() |> ignore
    
                        // Say it back to caller
                        channel.FilePlayer.Say("Hello, this is the quick start application for {0}. " + 
                                               "Have a good day. Goodbye.", tts) |> ignore
                    with 
                        | _ as e -> 
                            obj.Trace.TraceError("Exception thrown {0}", e.Message)
                            reply <- ReturnCode.ExceptionThrown
                finally
                    channel.HangUp() |> ignore
    
                obj.Trace.TraceInfo("Completed with return code {0}", reply)
                (int)reply
    
                
            // Convert the pin code to comma-separated digits.
            member obj.GetTtsFromPinCode(pinCode : string) : string =
                ", " + pinCode.Chars(0).ToString() + obj.GetTtsFromPinCode(pinCode.Substring(1))
     
    
            // Get suitable string for TTS based on SIP username in supplied callTo.
            // The SIP username must start with "sip:".
            // If next characters are "--" and the remaining 8 digits are numeric then read as a pin code.
            member obj.GetTtsFromUsername(callTo : string) : string =
                // check we have a sane callTo
                let splits : string [] = callTo.Split('@')
                if splits.Length <> 2 then
                    "an invalid SIP username"
                elif splits.[0].StartsWith(sipPrefix) then
                    "an invalid SIP username"
                else
                    // Remove the Sip:
                    let username : string = splits.[0].Substring(sipPrefix.Length)
                
                    // If we have a pin code, try to speak it nicely
                    if (username.StartsWith(pincodePrefix)) then
                        let pinCode : string = username.Substring(pincodePrefix.Length) 
    
                        // Is it the right length
                        if pinCode.Length <> pinCodeLength then
                            "a pin code that is not of length " + pinCodeLength.ToString()
                        else 
                            try
                                let pinCodeValues = Convert.ToInt32(pinCode)
                                obj.Trace.TraceInfo("Username [{0}] pin code [{1}]", username, pinCode)
                                "user pin code " + obj.GetTtsFromPinCode(pinCode)
                            with
                                | _ as e ->
                                    "an invalid pin code"
                    else
                        // Otherwise, just return the username
                        obj.Trace.TraceInfo("Username [{0}]", username)
                        "SIP username " + username