esl

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2022 License: BSD-2-Clause Imports: 11 Imported by: 0

README

Description

esl is a go library to connect to freeSWITCH via esl.

Installation

Installation can be done as usual:

$ go get github.com/vma/esl

How it works

esl.NewConnection create a new esl connection and take a ConnectionHandler interface which defines the callbacks to handle the esl events.

Example of use

This simple example originate a call, park it and start music on hold when it is answered. When the call is hanged up, we close the connection, which ends the con.HandleEvents() loop.

package main

import (
        "fmt"
        "log"

        "github.com/vma/esl"
)

type Handler struct {
        CallId  string
        BgJobId string
}

const (
        Caller = "+33184850000"
        Callee = "+33184850001"
)

func main() {
        handler := &Handler{}
        con, err := esl.NewConnection("127.0.0.1:8021", handler)
        if err != nil {
                log.Fatal("ERR connecting to freeswitch:", err)
        }
        con.HandleEvents()
}

func (h *Handler) OnConnect(con *esl.Connection) {
        con.SendRecv("event", "plain", "ALL")
        h.CallId, _ = con.Api("create_uuid")
        log.Println("call id:", h.CallId)
        h.BgJobId, _ = con.BgApi("originate", "{origination_uuid="+h.CallId+
                ",origination_caller_id_number="+Caller+"}sofia/gateway/provider/"+Callee, "&park()")
        log.Println("originate bg job id:", h.BgJobId)
}

func (h *Handler) OnDisconnect(con *esl.Connection, ev *esl.Event) {
        log.Println("esl disconnected:", ev)
}

func (h *Handler) OnClose(con *esl.Connection) {
        log.Println("esl connection closed")
}

func (h *Handler) OnEvent(con *esl.Connection, ev *esl.Event) {
        log.Printf("%s - event %s %s %s\n", ev.UId, ev.Name, ev.App, ev.AppData)
        fmt.Println(ev) // send to stderr as it is very verbose
        switch ev.Name {
        case esl.BACKGROUND_JOB:
                log.Printf("bg job result:%s\n", ev.GetTextBody())
        case esl.CHANNEL_ANSWER:
                log.Println("call answered, starting moh")
                con.Execute("playback", h.CallId, "local_stream://moh")
        case esl.CHANNEL_HANGUP:
                hupcause := ev.Get("Hangup-Cause")
                log.Printf("call terminated with cause %s", hupcause)
                con.Close()
        }
}

TODO

  • add documentation
  • add tests
  • more usage examples

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetLogger added in v1.0.1

func SetLogger(l EslLogger)

set logger for print esl package inner message output

why a logger interface?

first, we cannot distinguish the local error (event parse or others)
or command reply error in one send-reply function, which means should
handle local error locally, but we need to let the pkg user to decide
where and how to print.

Types

type Command

type Command struct {
	Sync  bool
	UId   string
	App   string
	Args  string
	Loops uint
}

func (Command) Execute

func (cmd Command) Execute(con *Connection) (*Event, error)

Execute sends Command cmd over Connection and waits for reply. Returns the command reply event pointer or an error if any.

func (*Command) Serialize

func (cmd *Command) Serialize() []byte

Serialize formats (serializes) the command as expected by freeswitch.

type Connection

type Connection struct {
	Handler    ConnectionHandler
	Address    string
	Password   string
	Connected  bool
	MaxRetries int
	Timeout    time.Duration
	UserData   interface{}
	// contains filtered or unexported fields
}

func NewConnection

func NewConnection(host, passwd string, handler ConnectionHandler) (*Connection, error)

func (*Connection) Api

func (con *Connection) Api(cmd string, args ...string) (string, error)

send api to FreeSWITCH by event socket, already start with `api ` support esl.Error type-assert

func (*Connection) Authenticate

func (con *Connection) Authenticate() error

Authenticate handles freeswitch esl authentication

func (*Connection) BgApi

func (con *Connection) BgApi(cmd string, args ...string) (string, error)

send background command to FreeSWITCH by event socket, already start with `bgapi ` support esl.Error type-assert

func (*Connection) Close

func (con *Connection) Close()

func (*Connection) ConnectRetry

func (con *Connection) ConnectRetry(mretries int) error

func (*Connection) Execute

func (con *Connection) Execute(app string, uuid string, params ...string) (*Event, error)

call an app on the leg which uuid is param uuid support esl.Error type-assert

func (*Connection) ExecuteLooped added in v1.0.2

func (con *Connection) ExecuteLooped(app string, uuid string, loops uint, params ...string) (*Event, error)

call an app on the leg which uuid is param uuid and call params loops times support esl.Error type-assert

func (*Connection) ExecuteLoopedSync added in v1.0.2

func (con *Connection) ExecuteLoopedSync(app string, uuid string, loops uint, params ...string) (*Event, error)

call an app on the leg which uuid is param uuid this app will not be interrupted by other applications, and call params loops times support esl.Error type-assert

func (*Connection) ExecuteSync

func (con *Connection) ExecuteSync(app string, uuid string, params ...string) (*Event, error)

call an app on the leg which uuid is param uuid this app will not be interrupted by other applications support esl.Error type-assert

func (*Connection) HandleEvents

func (con *Connection) HandleEvents() error

dead forloop, unless connection lost support esl.Error type-assert

func (*Connection) MustSendRecv

func (con *Connection) MustSendRecv(cmd string, args ...string) *Event

must send and receive command, or fatal the process

func (*Connection) SendEvent

func (con *Connection) SendEvent(cmd string, headers map[string]string, body []byte) (*Event, error)

send event to event socket support esl.Error type-assert

func (*Connection) SendRecv

func (con *Connection) SendRecv(cmd string, args ...string) (*Event, error)

send to FreeSWITCH and get result support esl.Error type-assert

func (*Connection) Write

func (con *Connection) Write(b []byte) (int, error)

type ConnectionHandler

type ConnectionHandler interface {
	OnConnect(con *Connection)
	OnEvent(con *Connection, ev *Event)
	OnDisconnect(con *Connection, ev *Event)
	OnClose(con *Connection)
}

type Error added in v1.0.4

type Error struct {
	Original error
	Stack    string
}

connection write/read may need a way to judge network error type here is the solution to:

  1. keep original error
  2. no SendRecv/Api/BgApi method signature modifications

if you want original error, please use type-switch

func (*Error) Error added in v1.0.4

func (e *Error) Error() string

func (*Error) WithStack added in v1.0.4

func (e *Error) WithStack(more string)

type EslLogger added in v1.0.1

type EslLogger interface {
	Printf(fmt string, v ...interface{})
	Fatal(v ...interface{})
}

type Event

type Event struct {
	UId     string
	Name    EventName
	App     string
	AppData string
	Stamp   int
	Type    EventType
	Header  MIMEMap
	Body    MIMEMap
	RawBody []byte
}

func NewEventFromReader

func NewEventFromReader(r *bufio.Reader) (*Event, error)

func (Event) Get

func (e Event) Get(header string) string

Get retrieves the value of header from Event header or (if not found) from Event body. The value is returned unescaped and is empty if not found anywhere.

func (*Event) GetTextBody

func (e *Event) GetTextBody() string

func (Event) String

func (e Event) String() string

type EventName

type EventName int
const (
	CUSTOM EventName = iota
	CLONE
	CHANNEL_CREATE
	CHANNEL_DESTROY
	CHANNEL_STATE
	CHANNEL_CALLSTATE
	CHANNEL_ANSWER
	CHANNEL_HANGUP
	CHANNEL_HANGUP_COMPLETE
	CHANNEL_EXECUTE
	CHANNEL_EXECUTE_COMPLETE
	CHANNEL_HOLD
	CHANNEL_UNHOLD
	CHANNEL_BRIDGE
	CHANNEL_UNBRIDGE
	CHANNEL_PROGRESS
	CHANNEL_PROGRESS_MEDIA
	CHANNEL_OUTGOING
	CHANNEL_PARK
	CHANNEL_UNPARK
	CHANNEL_APPLICATION
	CHANNEL_ORIGINATE
	CHANNEL_UUID
	API
	LOG
	INBOUND_CHAN
	OUTBOUND_CHAN
	STARTUP
	SHUTDOWN
	PUBLISH
	UNPUBLISH
	TALK
	NOTALK
	SESSION_CRASH
	MODULE_LOAD
	MODULE_UNLOAD
	DTMF
	MESSAGE
	PRESENCE_IN
	NOTIFY_IN
	PRESENCE_OUT
	PRESENCE_PROBE
	MESSAGE_WAITING
	MESSAGE_QUERY
	ROSTER
	CODEC
	BACKGROUND_JOB
	DETECTED_SPEECH
	DETECTED_TONE
	PRIVATE_COMMAND
	HEARTBEAT
	TRAP
	ADD_SCHEDULE
	DEL_SCHEDULE
	EXE_SCHEDULE
	RE_SCHEDULE
	RELOADXML
	NOTIFY
	PHONE_FEATURE
	PHONE_FEATURE_SUBSCRIBE
	SEND_MESSAGE
	RECV_MESSAGE
	REQUEST_PARAMS
	CHANNEL_DATA
	GENERAL
	COMMAND
	SESSION_HEARTBEAT
	CLIENT_DISCONNECTED
	SERVER_DISCONNECTED
	SEND_INFO
	RECV_INFO
	RECV_RTCP_MESSAGE
	CALL_SECURE
	NAT
	RECORD_START
	RECORD_STOP
	PLAYBACK_START
	PLAYBACK_STOP
	CALL_UPDATE
	FAILURE
	SOCKET_DATA
	MEDIA_BUG_START
	MEDIA_BUG_STOP
	CONFERENCE_DATA_QUERY
	CONFERENCE_DATA
	CALL_SETUP_REQ
	CALL_SETUP_RESULT
	CALL_DETAIL
	DEVICE_STATE
	ALL
)

func EventNameString

func EventNameString(s string) (EventName, error)

func (EventName) String

func (i EventName) String() string

type EventType

type EventType int
const (
	EventError EventType = iota
	EventState
	EventConnect
	EventAuth
	EventCommandReply
	EventApiResponse
	EventDisconnect
	EventGeneric
)

type MIMEMap

type MIMEMap struct {
	Map       textproto.MIMEHeader
	IsEscaped bool
}

func (MIMEMap) Get

func (m MIMEMap) Get(key string) string

func (MIMEMap) String

func (m MIMEMap) String() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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