miércoles, 25 de febrero de 2009

Asterisk-Java

Asterisk-Java

El paquete Asterisk-Java consiste de un set de clases Java que le permiten facilmente construir aplicaciones Java que interactua con servidores PBX Asterisk. Asterisk-Java soporta ambas interfaces que Asterisk provee para este escenario: The FastAGI protocol and the Manager API.

La implementacion FastAGI soporta todos los commands actualmente habiles de Asterisk.

El Manager API implementation soporra recibir eventos del Asterisk server (e.g. call progess, registered peers, channel state) y enviar acciones a Asterisk (e.g. originate call, agent login/logoff, start/stop voice recording).

A complete list of the available events and actions is available in the javadocs.

Asterisk-Java is available under Apache license from http://asterisk-java.org/.

Referencia

Asterisk-Java es usado en varios entornos comerciales y por los siguientes Open Source projects:
  • Asterisk-IM: A plugin for the Jive Messenger XMPP (jabber) server. It provides integrated presence between your IM client and phone, notification of incoming calls by IM and originate calls from supported IM clients.
  • Asterisk Desktop Manager (ADM): A desktop application that will allow for automatic on-call volume reduction, one click dial from clipboard, integrated phonebook and more.

Asterisk manager API

The Asterisk Manager API


The Asterisk Manager allows a client program to connect to an Asterisk instance and issue commands or read PBX events over a TCP/IP stream. Integrators will find this particularly useful when trying to track the state of a telephony client inside Asterisk, and directing that client based on custom (and possibly dynamic) rules.

A simple "key: value" line-based protocol is utilized for communication between the connecting client and the Asterisk PBX. Lines are terminated using CRLF. For the sake of discussion below, we will use the term "packet" to describe a set of "key: value" lines that are terminated by an extra carriage return.

New in Asterisk 1.4: AJAM is a new JavaScript-based technology which allows web browsers or other HTTP enabled applications and web pages to directly access the Asterisk Manager Interface (AMI) via HTTP.


Protocol Behavior


The protocol has the following characteristics:

  • Before issuing commands to Asterisk, you must establish a manager session (see below).
  • Packets may be transmitted in either direction at any time after authentication.
  • The first line of a packet will have a key of "Action" when sent from the client, but "Event" or "Response" when sent from Asterisk to the client.
  • The order of lines within a packet is insignificant, so you may use your favorite programming language's native unordered dictionary type to efficiently store a single packet.
  • CRLF is used to delimit each line and a blank line (two CRLF in a row) indicates the end of the command which Asterisk is now expected to process.

Packet Types

The type of a packet is determined by the existence of one of the following keys:

  • Action: A packet sent by the connected client to Asterisk, requesting a particular Action be performed. There are a finite (but extendable) set of actions available to the client, determined by the modules presently loaded in the Asterisk engine. Only one action may be outstanding at a time. The Action packet contains the name of the operation to be performed as well as all required parameters.
  • Response: the response sent by Asterisk to the last action sent by the client.
  • Event: data pertaining to an event generated from within the Asterisk core or an extension module.
Generalmente el cliente envia un paquete Action al server Asterisk, quien procesa la operacion requerida y retorna el resultado (devuelve solo success o failure) en un paquete Response. Como no hay garantia del orden de respuesta el cliente usualmente incluye un parametro ActionID en cada Action packet que es enviado de vuelta por el Asterisk en el correspondiente paquete Response. De esta manera el cliente puede facilmente hacer match con la Accion y Respuesta mientras envia Actions en la tasa deseada sin tener que esperar por paquetes de respuesta de salida antes de enviar la proxima acción.
cada paquete son usados en 2 diferentes contextos: en el primero informan a clientes acerca del estado de cambios en Asterisk (Como nuevos canales que se inician creados y colgados o agentes que se loguean y desloguean) en la otra manera ellos son usados para transportar el response payload para acciones que devuelven una lista de datos. on the other hand they are used to transport the response payload for actions that return a list of data (actions que generan eventos). Cuando el cliente envia una accion generando eventos, Asterisk envia un paquete respuesta indicando sucesos y conteniendo una linea: "Response: Follows". Entonces se envia zero o mas eventos que contienen el actual payload y finalmente un evento de accion completa conteniendo el ActionID de el Action packet que disparó esto. An example of an event generating action is the Status action that triggers Status events for each active channel. When all Status events have been sent a terminating a StatusComplete event is sent.

Opening a Manager Session and Authenticating as a User


In order to access the Asterisk Manager functionality a user needs to establish a session by opening a TCP/IP connection to the listening port (usually 5038) of the Asterisk instance and logging into the manager using the 'Login' action. This requires a previously established user account on the Asterisk server. User accounts are configured in /etc/asterisk/manager.conf. A user account consists of a set of permitted IP hosts, an authentication secret (password), and a list of granted permissions.

There is a finite set of permissions, each may be granted with either "read", "write", or "read/write" granularity. If a client is granted the ability to read a given class, Asterisk will send it events of that class. If a client is granted the ability to write a given class, it may send actions of that class.

To login and authenticate to the manager, you must send a "Login" action, with your user name and secret (password) as parameters. Here is an example:

Action: login
Username: admin
Secret: god

If you do not need to subscribe to events being generated by Asterisk, you may also include the "Events: off" parameter, which will prevent event packets being sent to your connection. This is the equivalent of calling the "Events" action. Example:

Action: login
Username: admin
Secret: god
Events: off

Action Packets


When sending Asterisk an action, extra keys may be provided to further direct execution, for example, you may wish to specify a number to call, a channel to disconnect. Additionally, if your action causes Asterisk to execute an entry in the dialplan, you may wish to pass variables to the dialplan (available as of bug 1268). This is done exactly the same way you would send keys.

To send Asterisk an action, follow this simple format:

Action: <action type><CRLF>
<Key 1>: <Value 1><CRLF>
<Key 2>: <Value 2><CRLF>
...
Variable: <Variable 1>=<Value 1><CRLF>
Variable: <Variable 2>=<Value 2><CRLF>
...
<CRLF>

Manager Actions


Output from the CLI command show manager commands:
(For Asterisk 1.4 and greater, use manager show commands)




FastAGI


Implementa el Asterisk Gateway Interface (AGI) over TCP sockets. Ayuda a aliviar la carga del CPU del server Asterisk redireccionando recursos a otro server en la Red. Para indicar al server Asterisk a realizar una coneccion de red se deberá indicar el hostname or IP address of the server donde el FastAGI service is hosted and preface it with agi://:
exten => 5551212,1,AGI(agi://192.168.0.2)
Asterisk intenta conectarse al especificado server sobre el port 4573. El port tambien puede ser especificado si se escoge el servicio AGI en otro port :

exten => 5551212,1,AGI(agi://192.168.0.2:8675)

Un request puede tambien ser especificado en la llamada FastAGI , tal que podemos tener multiples AGIs en una unica locacion de red.
This request allows the FastAGI service to differentiate between different locations in the dialplan. For example:

exten => 5551212,1,AGI(agi://192.168.0.2/GetCallerRecord)

and:

exten => 5551212,1,AGI(agi://192.168.0.2/CallerWantsCustomerService)
The request portion of these calls will be received by the FastAGI service as the agi_network_script AGI variable. Asterisk will also include the agi_network AGI variable. For example, the FastAGI in the previous example would receive something like this when called by Asterisk:

agi_network: yes
agi_network_script: /CallerWantsCustomerService

Passing Arguments to FastAGI


Asterisk 1.2 & 1.4

With Asterisk 1.2 through 1.4, when using standard AGI, you can pass variables on the command line to your local scripts. This is not possible with FastAGI, however, but can be simulated using agi_network_script and a query syntax similar to that used by HTTP. For example:

exten => 5551212,1,AGI(agi://192.168.0.2/GetCallerRecord?extension=${EXTEN})

It is the responsibility of your FastAGI framework to parse this information out of the agi_network_script variable. Some FastAGI implementations already do this for you, so be sure to check the documentation for your particular framework.

Error Handling

Asterisk 1.4 & 1.6.x

As of Asterisk 1.4 a new channel variable, AGISTATUS, is set to SUCCESS upon successful execution of an AGI. If there was a problem connecting to the FastAGI service, the channel variable is set to FAILURE, allowing the dialplan to perform alternate steps as not to interrupt the call flow. If the calling channel hangs up during execution of the AGI, AGISTATUS is set to HANGUP.

FastAGI Servers


Java


AGI enhancements

asterisk-agi-audiotx

This is an extension module for the Asterisk Gateway Interface (AGI) that adds commands to allow the transfer of audio files to and from Asterisk via the AGI session. This is useful when using FastAGI from a remote host; sounds recorded by Asterisk may be retrieved by remote FastAGI-providing service, for example, or sound files required by the remote service may be dynamically added to the Asterisk server.
This module adds the following AGI commands:
  • PUT SOUNDFILE
  • GET SOUNDFILE
  • ISEXISTING SOUNDFILE

jueves, 25 de diciembre de 2008

Lanzar llamadas en forma automatica

[1] http://www.voip-info.org/wiki/view/Asterisk+cli+originate
[2] http://www.voip-info.org/wiki/view/Asterisk+manager+API
[3] http://www.voip-info.org/tiki-index.php?page=Asterisk+auto-dial+out

En mi caso funcionò :
originate SIP/Sitatel/13582352 extension 1001
se realizò la llamada a mi rpm y luego lo conectò a la extension 1001 (primero timbrò el celular y luego el anexo).
desde linux :
FaJoa:~# asterisk -rx "originate SIP/Sitatel/13582352 extension 1001"

originate SIP/Sitatel/13582352 application Festival " el circuito 22352 esta caido, el circuito 22352 esta caido"
llama al celu y lee los mensajes, pero con un tono robotizado, falta afinar ese tema.

para instalar festival:
http://phylevn.mexrom.net/index.php/Blog/CommentsRSS/id/index.php/blog/show/67.html

http://www.voztovoice.org/?q=node/97

Festival con voces en español:
Las voces las podeis descargar desde aquí:
http://forja.guadalinex.org/repositorio/frs/?group_id=21&release_id=110

jueves, 18 de diciembre de 2008

Troubleshooting SIP Trunks with Cisco CallManager 5.x

El rfc 2833 (DTMF) Media Termination Point (MTP) pasa a travéz caracteristicas de transparente DTMF tonos entre SIP endpoint que requieran o transcoding o el uso de RSVP (Resource Reservation Protocol )

SIP with CallManager 5.x
Introduce mejoras a SIP Trunks y sobrelleva las limitantes de release anteriores como un simple codec soportado, carecer de soporte de video y el obligado soporte MTP Media terminal point para RFC2833 DTMF.
The other enhancements to SIP trunks in Cisco Unified CallManager 5.0 are the support for REFER, header replacement, Subscribe/Notify, message waiting indication (MWI), MTP removal, video support, multiple SIP trunks per inbound port number, SIP Redirection 3XX, transport layer security (TLS), digest authentication, call preservation, and T.38 fax relay.

Media Termination Point for SIP Trunks
Se puede configurar dispositivos SIP en el CallManager (lineas y trunks) a siempre usar MTP, si los parametros seteados no son usar MTP (por default), cisco localiza dinamicamente un MTP si el metodo DTMF para llamadas no son compatibles.
Por ejemplo SCCP phones soportan sólamente out-of-band DTMF.
Telefonos SIP (model 7905, 7912, 7940, 7960) soportan RFC 2833.
Como los metodos DTMF no son los mismos, cisco localiza un MTP.
Si un SCCP phone soporta tanto RFC2833 y out-of-band como es el caso del 7971, cisco no localiza un MTP por que ambos phones soportan RFC2833.
con el mismo metodo de DTMF soportado en ambos telefonos, no es necesario un MTP.

Understanding Session Initiation Protocol (SIP)

Se utilizan los siguientes componentes:
•SIP Proxy Server— Trabaja como un dispositivo intermedio que recibe request SIP de un cliente y forwards el request a nombre del cliente. Puede proveer funciones como authentication, authorization, network access control, routing, reliable request retransmission, and security.
•Redirect Server— Provee al cliente con info acerca del next hop o hops que un mensaje debe tomar, el cliente contacta con el next hop server o user agent server directamente.
•Registrar Server— El server de registro procesa request de user agent clients para registro de su ubicacion actual. Redirect o Proxy server a menudo contienen servidores de registro.
•User Agent (UA)— Una combinacion de user agent client (UAC) y user agent server (UAS) que inicia y recibe SIP request. Un UAC inicia un SIP request. Un UAS es una aplicacion server que contacta al user cuando este recibe yn SIP request. El UAS devuelve yna respuesta a nombre de el user. Cisco CallManager puede actuar como ambos server o cliente (un back-to-back user agent).

SIP usa un request/response metodo para establecer comunicaciones entre varios componentes en la red y ultimadamente establecer una llamada o sesion entre 2 o mas endpoints. Una simple sesion puede envolver varios clientes y servers.

identificacion de usuarios en una red SIP trabaja con :
•A unique phone or extension number.
•A unique SIP address that appears similar to an e-mail address and uses the format sip:@. The user ID can be either a user name or an E.164 address. Cisco CallManager only supports E.164 addresses; it does not support email addresses.

SIP and Cisco CallManager
Todos los protocolos requieren una interfaz de señalizacion (trunk) o un gateway sean creados para aceptar y originar llamadas. Para SIP el usuario debe crear una interface de señalizacion.
Interfaces de señalizacion SIP conectan redes Cisco CallManager y redes SIP que son atendidas por un SIP Proxy Server. Como con otros protocolos, componentes SIP encajan bajo la capa de dispositivos (layer device) de una arquitectura CallManager.
Como en el caso de H323, multiples logicas interfaces de señalizacion SIP pueden ser configurados en la base de datos del CallManager y asociados a route groups. route lists y route patterns.
Para proveer redundancia, en el caso de falla de una interface logica SIP, otra interface logica SIP debe proveer servicio en el mismo route group list. tambien podemos asignar multiples modos Cisco CallManager bajo un pool de dispositivos interfaces de señalizacion SIP.
Interfaces de señalizacion SIP usan enrutamiento basado en puerto, con una interface de señalizacion SIP conectando a una red SIP. Cisco CallManager aceptan llamadas de un dispositivo SIP siempre y cuando el mensaje arrive en el configurado puerto de entrada. Cuando se configure multiple interfaces de señalizacion, configure un unico incomming-port por cada interface SIP. Utilizar el mismo puerto para varias interfaces de señalización pueden causar una alarma.


SIP Networks

Media Termination Point (MTP) Devices

Cisco CallManager requiere un RFC2833 dual tone multifrequency (DTMF) compatible con dispositivos MTP para hacer llamadas SIP.
El actual standar para SIP usa tipo de payload in-band RTP para indicar tonos DTMF. AVVID componentes como telefonos SCCP IP soportan solo payload DTMF out-of-band . Por lo tanto un dispositivo MTP compatible con RFC2833 actua como un translator entre inband and out-of-band DTMF.

DTMF Relay Calls Between SIP Endpoints and Cisco CallManager
Basado en el RFC 2833 el estandar SIP usa tipo de payload in-band para indicar tonos DTMF. Componentes AVVID como SCCP IP Phone no soportan in-band payload. Un dispositivo MTP compatible con RFC 2833 monitorea para los tipos de payloads y traduce entre in-band y out-band los tipos de payload.
El siguiente flujo de llamada muestra el dispositivo software MTP procesando inband DTMF digitos de un SIP Phone para comunicarse con Gateway PRI, el stream RTP lleva RFC 2833 DTMF , como indica por un dinamico tipo de payload.



1. The SIP Phone initiates a payload type response when the user enters a number on the keypad. The SIP Phone transfers the DTMF in-band digit (per RFC 2833) to the MTP device.
2. The MTP device extracts the in-band DTMF digit and passes the digit out of band to Cisco CallManager.
3. Cisco CallManager then relays the DTMF digit out of band to the gateway or IVR system.

Generating DTMF Digits

1. The SCCP IP Phone user presses buttons on the keypad. Cisco CallManager collects the out-of-band digits from the SCCP IP phone.
2. Cisco CallManager passes the out-of-band digits to the MTP device.
3. The MTP device converts the digits to RFC 2833 RTP compliant inband digits and forwards them to the SIP client.


Trunk Configuration Checklist
Configuration Steps
Procedures and Related Topics
Step 1
Create a SIP trunk.
For outgoing calls, configure the destination address (the address of the SIP Proxy Server).
Configure the destination port.
Configure a unique incoming port for each SIP interface.
Adding a Trunk, Cisco CallManager Administration Guide
Trunk Configuration Settings, Cisco CallManager Administration Guide

Step 2
Verify the RFC 2833 compliant MTP device is configured.
Trunk Configuration Settings, Cisco CallManager Administration Guide
In the trunk configuration, the MTP field is always checked. SIP requires an RFC 2833 compliant MTP device. For more information on MTP, see Media Termination Point Configuration, Cisco CallManager Administration Guide.

Step 3
Assign to a Route Pattern, Route Group, or Route List, if needed.
Route Pattern/Hunt Pilot Configuration,Cisco CallManager Administration Guide
Route Group Configuration, Cisco CallManager Administration Guide
Route/Hunt List Configuration, Cisco CallManager Administration Guide

Step 4
Configure SIP timers, counters, and service parameters, if necessary.
Service Parameters Configuration, Cisco CallManager Administration Guide.
For specific configurable values, see SIP Service Parameters.

Step 5
Verify the Annunciator is active, if necessary.
Annunciator Configuration, Cisco CallManager Administration Guide.

Step 6
If a SIP Proxy server is used as the destination address, configure static routes to point to all IP addresses or domain names of the SIP interface Call Manager Group.

Trunk Configuration Settings, Cisco CallManager Administration Guide
The device pool field can be an IP address, fully-qualified domain name (FQDN), or DNS SRV name.

Cisco CallManager Trunk SIP

En un entorno de procesos de llamadas distribuido, Cisco Callmanager se comunica con otro cluster Cisco Callmanager, PSTN u otro dispositivo como PBX, utilizando trunk signaling y gateway de voz.

Configuracion TRUNK
la configuracion Trunk en Cisco CallManager depende del diseño de red y protocolos de control de llamadas que son usados en IP WAN. Todos los protocolos requieren que un signaling interface (trunk) o un gateway debe ser creado para aceptar y originar llamadas. Se especifica el tipo de signaling interface cuando se configura el gateway en CallManager Cisco. Por ejemplo al configurar conecciones QSIG al CallManager se debe añadir un MCGP voice gateway que soporte protocol QSIG. Se configura el E1 PRI trunk interface a usar el tipo de protocol QSIG.

Trunk Types in Cisco CallManager Administration
•H.225 Trunk (Gatekeeper Controlled)
In a H.323 network that uses gatekeepers, use an H.225 trunk with gatekeeper control to configure a connection to a gatekeeper for access to other Cisco CallManager clusters and to H.323 devices. An H.225 trunk can communicate with any H.323 gatekeeper-controlled endpoint. When you configure an H.323 gateway with gatekeeper control in Cisco CallManager Administration, use an H.225 trunk. To choose this method, use Device > Trunk and choose H.225 Trunk (Gatekeeper Controlled).

•Intercluster Trunk (Gatekeeper Controlled)
In a distributed call-processing network with gatekeepers, use an intercluster trunk with gatekeeper control to configure connections between clusters of Cisco CallManager systems. Gatekeepers provide call admission control and address resolution for intercluster calls. A single intercluster trunk can communicate with all remote clusters. To choose this method, use Device > Trunk and choose Inter-Cluster Trunk (Gatekeeper Controlled) in Cisco CallManager Administration.

•Intercluster Trunk (Non-Gatekeeper Controlled)
In a distributed network that has no gatekeeper control, you must configure a separate intercluster trunk for each device pool in a remote cluster that the local Cisco CallManager can call over the IP WAN. The intercluster trunks statically specify the IP addresses or host names of the remote devices.To choose this method, use Device > Trunk and choose Inter-Cluster Trunk (Non-Gatekeeper Controlled) in Cisco CallManager Administration.

•SIP Trunk
Usamos SIP Trunk para configurar una interface de señalización con el Cisco CallManager para llamadas SIP.
SIP trunks (or signaling interfaces) connect Cisco CallManager clusters with a SIP proxy server.
Un SIP signaling interface usa port-based routing y Cisco CallManager acepta llamadas de cualquier gateway siempre y cuando los mensajes SIP arrivan al puerto que esta configurado como una interface de señalizacion SIP. La interface de señalización SIP usa request y responses para establecer, mantener y terminar llamadas entre 2 o más endpoints.
Para escoger este metodo: use Device > Trunk and escoger SIP Trunk in Cisco CallManager Administration.
You must also configure route groups and route patterns that use the SIP trunks to route the SIP calls.