agi

package module
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2024 License: Apache-2.0 Imports: 13 Imported by: 0

README

Asterisk AGI library for Go (golang)

Build Status

This is an Asterisk AGI interface library which may be used for both classical AGI, with a standalone executable, or FastAGI, with a TCP server.

package main

import "github.com/CyCoreSystems/agi"

func main() {
   a := agi.NewStdio()

   a.Answer()
   err := a.Set("MYVAR", "foo")
   if err != nil {
      panic("failed to set variable MYVAR")
   }
   a.Hangup()
}

Standalone AGI executable

Use agi.NewStdio() to get an AGI reference when running a standalone executable.

For a TCP server, register a HandlerFunc to a TCP port:

package main

import "github.com/CyCoreSystems/agi"

func main() {
   agi.Listen(":8080", handler)
}

func handler(a *agi.AGI) {
   defer a.Close()

   a.Answer()
   err := a.Set("MYVAR", "foo")
   if err != nil {
      panic("failed to set variable MYVAR")
   }
   a.Hangup()
}

Documentation

Index

Constants

View Source
const (
	// StatusOK indicates the AGI command was
	// accepted.
	StatusOK = 200

	// StatusInvalid indicates Asterisk did not
	// understand the command.
	StatusInvalid = 510

	// StatusDeadChannel indicates that the command
	// cannot be performed on a dead (hangup) channel.
	StatusDeadChannel = 511

	// StatusEndUsage indicates...TODO
	StatusEndUsage = 520
)

Variables

View Source
var Err511CommandNotPermitted = errors.New("Command Not Permitted on a dead channel or intercept routine")

Err511CommandNotPermitted indicates we have received error 511 Command Not Permitted

View Source
var Err511GenericError = errors.New("Generic 511 Error")

Err511GenericError indicates we have received generic 511 error

View Source
var ErrHangup = errors.New("hangup")

ErrHangup indicates the channel hung up during processing

View Source
var ErrTimeout = errors.New("timeout")

ErrTimeout indicates the get data command ends with timeout during processing

Functions

func Listen

func Listen(addr string, handler HandlerFunc) error

Listen binds an AGI HandlerFunc to the given TCP `host:port` address, creating a FastAGI service.

Types

type AGI

type AGI struct {
	// Variables stored the initial variables
	// transmitted from Asterisk at the start
	// of the AGI session.
	Variables map[string]string
	// contains filtered or unexported fields
}

AGI represents an AGI session

func New

func New(r io.Reader, w io.Writer) *AGI

New creates an AGI session from the given reader and writer.

func NewConn

func NewConn(conn net.Conn) *AGI

NewConn returns a new AGI session bound to the given net.Conn interface

func NewEAGI

func NewEAGI() *AGI

NewEAGI returns a new AGI session to stdin, the EAGI stream (FD=3), and stdout.

func NewStdio

func NewStdio() *AGI

NewStdio returns a new AGI session to stdin and stdout.

func NewWithEAGI

func NewWithEAGI(r io.Reader, w io.Writer, eagi io.Reader) *AGI

NewWithEAGI returns a new AGI session to the given `os.Stdin` `io.Reader`, EAGI `io.Reader`, and `os.Stdout` `io.Writer`. The initial variables will be read in.

func (*AGI) Answer

func (a *AGI) Answer() error

Answer answers the channel

func (*AGI) ApplyLogger added in v0.7.1

func (a *AGI) ApplyLogger(l *zap.Logger)

ApplyLogger setup external logger for low-level logging

func (*AGI) Close

func (a *AGI) Close() (err error)

Close closes any network connection associated with the AGI instance

func (*AGI) Command

func (a *AGI) Command(cmd ...string) (resp *Response)

Command sends the given command line to stdout and returns the response. TODO: this does not handle multi-line responses properly

func (*AGI) CommandNoParse added in v0.7.1

func (a *AGI) CommandNoParse(cmd ...string) (resp *Response)

CommandNoParse sends the given command line to stdout and returns the response. TODO: this does not handle multi-line responses properly

func (*AGI) EAGI

func (a *AGI) EAGI() io.Reader

EAGI enables access to the EAGI incoming stream (if available).

func (*AGI) Exec

func (a *AGI) Exec(cmd ...string) (string, error)

Exec runs a dialplan application

func (*AGI) ExecBackground added in v0.7.1

func (a *AGI) ExecBackground(filePath ...string) (string, error)

ExecBackground play a given audio filenames while waiting for digits of an extension to go to.

func (*AGI) ExecPlayback added in v0.7.1

func (a *AGI) ExecPlayback(filePath ...string) (string, error)

ExecPlayback plays back given filenames

func (*AGI) Get

func (a *AGI) Get(key string) (string, error)

Get gets the value of the given channel variable

func (*AGI) GetData

func (a *AGI) GetData(sound string, timeout time.Duration, maxDigits int) (digits string, err error)

GetData plays a file and receives DTMF, returning the received digits

func (*AGI) Hangup

func (a *AGI) Hangup() error

Hangup terminates the call

func (*AGI) Log added in v0.7.1

func (a *AGI) Log(logLevel, msg string) error

Log Sends an arbitrary text message to a selected log level

func (*AGI) LogDTMF added in v0.7.1

func (a *AGI) LogDTMF(msg string) error

func (*AGI) LogDebug added in v0.7.1

func (a *AGI) LogDebug(msg string) error

func (*AGI) LogError added in v0.7.1

func (a *AGI) LogError(msg string) error

func (*AGI) LogNotice added in v0.7.1

func (a *AGI) LogNotice(msg string) error

func (*AGI) LogVerbose added in v0.7.1

func (a *AGI) LogVerbose(msg string) error

func (*AGI) LogWarning added in v0.7.1

func (a *AGI) LogWarning(msg string) error

func (*AGI) MRCPRecog added in v0.2.0

func (a *AGI) MRCPRecog(grammar string, opts string) (*RecognitionResult, error)

MRCPRecog listens for speech and optionally plays a prompt. (requires UniMRCP app and resource to be compiled and loaded in Asterisk).

func (*AGI) MRCPSynth added in v0.2.0

func (a *AGI) MRCPSynth(prompt string, opts string) (res *SynthResult, err error)

MRCPSynth synthesizes speech for a prompt via MRCP. (requires UniMRCP app and resource to be compiled and loaded in Asterisk).

func (*AGI) RecognitionConfidence added in v0.2.0

func (a *AGI) RecognitionConfidence(index int) (int, error)

RecognitionConfidence returns the confidence level (0-100 with 100 being best) from the last MRCP speech recognition process. The index is based on the set of results ordered by decreasing confidence. Thus index 0 is the best match.

func (*AGI) RecognitionGrammar added in v0.2.0

func (a *AGI) RecognitionGrammar(index int) (string, error)

RecognitionGrammar returns the grammar which was matched from the last MRCP speech recognition process. The index is based on the set of result ordered by decreasing confidence. Thus index 0 is the best match.

func (*AGI) RecognitionInput added in v0.2.0

func (a *AGI) RecognitionInput(index int) (string, error)

RecognitionInput returns the detected input from the last MRCP speech recognition process. The index is based on the set of results ordered by decreasing confidence. Thus index 0 is the best match.

func (*AGI) RecognitionInterpretation added in v0.2.0

func (a *AGI) RecognitionInterpretation(index int) (ret *RecognitionInterpretation, err error)

RecognitionInterpretation returns the speech interpretation from the last MRCP speech recognition process. The index is based on the set of results ordered by decreasing confidence. Thus index 0 is the best match.

func (*AGI) Record

func (a *AGI) Record(name string, opts *RecordOptions) error

Record records audio to a file

func (*AGI) SayAlpha

func (a *AGI) SayAlpha(label string, escapeDigits string) (digit string, err error)

SayAlpha plays a character string, annunciating each character.

func (*AGI) SayDate

func (a *AGI) SayDate(when time.Time, escapeDigits string) (digit string, err error)

SayDate plays a date

func (*AGI) SayDateTime

func (a *AGI) SayDateTime(when time.Time, escapeDigits string, format string) (digit string, err error)

SayDateTime plays a date using the given format. See `voicemail.conf` for the format syntax; defaults to `ABdY 'digits/at' IMp`.

func (*AGI) SayDigits

func (a *AGI) SayDigits(number string, escapeDigits string) (digit string, err error)

SayDigits plays a digit string, annunciating each digit.

func (*AGI) SayNumber

func (a *AGI) SayNumber(number string, escapeDigits string) (digit string, err error)

SayNumber plays the given number.

func (*AGI) SayPhonetic

func (a *AGI) SayPhonetic(phrase string, escapeDigits string) (digit string, err error)

SayPhonetic plays the given phrase phonetically

func (*AGI) SayTime

func (a *AGI) SayTime(when time.Time, escapeDigits string) (digit string, err error)

SayTime plays the time part of the given timestamp

func (*AGI) Set

func (a *AGI) Set(key, val string) error

Set sets the given channel variable to the provided value.

func (*AGI) SetLogger added in v0.6.0

func (a *AGI) SetLogger(l *zap.Logger) error

SetLogger setup external logger for low-level logging

func (*AGI) SetRaw added in v0.7.1

func (a *AGI) SetRaw(key, val string) error

SetRaw sets the given channel settings to the provided value.

func (*AGI) Status

func (a *AGI) Status() (State, error)

Status returns the channel status

func (*AGI) StreamFile

func (a *AGI) StreamFile(name string, escapeDigits string, offset int) (digit string, err error)

StreamFile plays the given file to the channel

func (*AGI) SynthAndRecog added in v0.2.0

func (a *AGI) SynthAndRecog(prompt string, grammar string, opts string) (*RecognitionResult, error)

SynthAndRecog plays a synthesized prompt and waits for speech to be recognized (requires UniMRCP app and resource to be compiled and loaded in Asterisk).

func (*AGI) Verbose

func (a *AGI) Verbose(msg string, level int) error

Verbose logs the given message to the verbose message system

func (*AGI) Verbosef added in v0.6.0

func (a *AGI) Verbosef(format string, args ...interface{}) error

Verbosef logs the formatted verbose output

func (*AGI) WaitForDigit

func (a *AGI) WaitForDigit(timeout time.Duration) (digit string, err error)

WaitForDigit waits for a DTMF digit and returns what is received

func (*AGI) WaitForSilence added in v0.7.1

func (a *AGI) WaitForSilence(silenceRequiredMsec int, iterations int, timeout time.Duration) (string, error)

WaitForSilence waits for a specified amount of silence

type HandlerFunc

type HandlerFunc func(*AGI)

HandlerFunc is a function which accepts an AGI instance

type RecognitionInterpretation added in v0.2.0

type RecognitionInterpretation struct {

	// Confidence indicates how sure the MRCP server's engine was that the result was properly recognized.  It is a value from 0-100, with the highest value indicating the most confidence.
	Confidence int

	// Input is the textual representation of the recognized speech
	Input string

	// Grammar indicates the grammar or recognition rule which was matched
	Grammar string
}

RecognitionInterpretation describes a specific interpretation of speech input

type RecognitionResult added in v0.2.0

type RecognitionResult struct {

	// Status indicates the value of RECOG_STATUS, which is one of "OK", "ERROR", or "INTERRUPTED", which indicates whether the recognition process completed.
	//
	//  "OK" - the recognition executed properly
	//
	//  "ERROR" - the recognition failed to execute
	//
	//  "INTERRUPTED" - the call ended before the recognition could complete its execution
	//
	Status string

	// Cause indicates the value of RECOG_COMPLETION_CAUSE, which indicates whether speech was recognized.
	//
	// Possible values are:
	//
	// 0 - Success; speech was recognized
	//
	// 1 - No Match; speech was detected but it did not match anything in the grammar
	//
	// 2 - No Input; no speech was detected
	//
	Cause int

	// Result is the value of RECOG_RESULT, which contains the NLSML result (unparsed string) received from the MRCP server.
	Result string
}

RecognitionResult describes the result of an MRCP speech recognition action

type RecordOptions

type RecordOptions struct {
	// Format is the format of the audio file to record; defaults to "wav".
	Format string

	// EscapeDigits is the set of digits on receipt of which will terminate the recording. Default is "#".  This may not be blank.
	EscapeDigits string

	// Timeout is the maximum time to allow for the recording.  Defaults to 5 minutes.
	Timeout time.Duration

	// Silence is the maximum amount of silence to allow before ending the recording.  The finest resolution is to the second.   0=disabled, which is the default.
	Silence time.Duration

	// Beep controls whether a beep is played before starting the recording.  Defaults to false.
	Beep bool

	// Offset is the number of samples in the recording to advance before storing to the file.  This is means of clipping the beginning of a recording.  Defaults to 0.
	Offset int
}

RecordOptions describes the options available when recording

type Response

type Response struct {
	Error        error  // Error received, if any
	Status       int    // HTTP-style status code received
	Result       int    // Result is the numerical return (if parseable)
	ResultString string // Result value as a string
	Value        string // Value is the (optional) string value returned
}

Response represents a response to an AGI request.

func (*Response) Err

func (r *Response) Err() error

Err returns the error value from the response

func (*Response) Res added in v0.7.1

func (r *Response) Res() (string, error)

Res returns the ResultString of a Response, as well as any error encountered. Depending on the command, this is sometimes more useful than Val()

func (*Response) Val

func (r *Response) Val() (string, error)

Val returns the response value and error

type State

type State int

State describes the Asterisk channel state. There are mapped directly to the Asterisk enumerations.

const (
	// StateDown indicates the channel is down and available
	StateDown State = iota

	// StateReserved indicates the channel is down but reserved
	StateReserved

	// StateOffhook indicates that the channel is offhook
	StateOffhook

	// StateDialing indicates that digits have been dialed
	StateDialing

	// StateRing indicates the channel is ringing
	StateRing

	// StateRinging indicates the channel's remote end is ringing (the channel is receiving ringback)
	StateRinging

	// StateUp indicates the channel is up
	StateUp

	// StateBusy indicates the line is busy
	StateBusy

	// StateDialingOffHook indicates digits have been dialed while offhook
	StateDialingOffHook

	// StatePreRing indicates the channel has detected an incoming call and is waiting for ring
	StatePreRing
)

type SynthResult added in v0.2.0

type SynthResult struct {

	// Status indicates whether the operation completed.
	//
	// Valid values are:
	//
	//   - "OK" : the synthesis operation succeeded
	//
	//   - "ERROR" : the synthesis operation failed
	//
	//   - "INTERRUPTED" : the channel disappeared during the synthesis operation
	//
	Status string

	// Cause is a numeric code indicating the reason for the status
	//
	// Known values are:
	//
	//   - 0 : Normal
	//
	//   - 1 : Barge-In occurred
	//
	//   - 2 : Parse failure
	//
	Cause int
}

SynthResult describes the result of an MRCP Synthesis operation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL