Comunicaciones Unificadas Con Elastix Vol. 1

479
Comunicaciones Unificadas con Elastix Vol. 1 http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.] Indice Portada Índice Introducción 1. Introducción a la telefonía 1.1 Breve historia de la telefonía Los albores de la telefonía Los problemas con las patentes El desarrollo de la tecnología telefónica 1.2 Los principios de la transmisión de voz Rango de frecuencias de la voz humana El micrófono Ancho de banda y capacidad de información 1.3 Digitalización de la voz Teorema de Nyquist 1.4 Redes orientadas a circuitos 1.5 Redes orientadas a paquetes 1.6 Red Pública Telefónica ( PSTN ) 1.7 Circuitos analógicos Señalización analógica DTMFs El teléfono analógico 1.8 Circuitos digitales La base DS-0 Circuitos T-carrier y E-carrier SONET y Circuitos Ópticos 1.9 Protocolos de Señalización Digital Señalización Asociada al Canal (CAS) Señalización de Canal Común (CCS) 2. Introducción a la VoIP 2.1 VoIP: una sopa de protocolos Clasificando los protocolos VoIP 2.2 Protocolo IP El Internet ¿Qué es el protocolo IP? Dirección IP Paquete IP Direccionamiento IP 2.3 Protocolos de transporte Protocolo TCP Protocolo UDP 2.4 Codificación de la voz Codecs 2.5 Sobrecarga de protocolos Comparativa de codecs 3. Linux para Administradores de Elastix 3.1 Introducción

Transcript of Comunicaciones Unificadas Con Elastix Vol. 1

Page 1: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.]

IndicePortada

Índice

Introducción

1. Introducción a la telefonía1.1 Breve historia de la telefonía

Los albores de la telefoníaLos problemas con las patentesEl desarrollo de la tecnología telefónica

1.2 Los principios de la transmisión de vozRango de frecuencias de la voz humanaEl micrófonoAncho de banda y capacidad de información

1.3 Digitalización de la vozTeorema de Nyquist

1.4 Redes orientadas a circuitos1.5 Redes orientadas a paquetes1.6 Red Pública Telefónica (PSTN)1.7 Circuitos analógicos

Señalización analógicaDTMFsEl teléfono analógico

1.8 Circuitos digitalesLa base DS-0Circuitos T-carrier y E-carrierSONET y Circuitos Ópticos

1.9 Protocolos de Señalización DigitalSeñalización Asociada al Canal (CAS)Señalización de Canal Común (CCS)

2. Introducción a la VoIP2.1 VoIP: una sopa de protocolos

Clasificando los protocolos VoIP2.2 Protocolo IP

El Internet¿Qué es el protocolo IP?Dirección IPPaquete IPDireccionamiento IP

2.3 Protocolos de transporteProtocolo TCPProtocolo UDP

2.4 Codificación de la vozCodecs

2.5 Sobrecarga de protocolosComparativa de codecs

3. Linux para Administradores de Elastix3.1 Introducción

Page 2: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.]

3.2 Línea de comandos de Linux3.3 Comandos básicos3.4 Sistema de archivos

OrganizaciónPermisos

3.5 RPMs y actualizaciones vía YumYum al rescate

4. Asterisk: Conceptos Esenciales4.1 ¿Qué es Asterisk?4.2 Breve historia de Asterisk4.3 Funcionalidad provista por Asterisk4.4 Funcionamiento de Asterisk

Directorios de AsteriskEstructura modular

4.5 El proyecto DAHDIBreve historia de DAHDI

4.6 Configuración de AsteriskArchivos de configuraciónComentarios en los archivos de configuración

4.7 Plan de marcado (dial plan)ContextosExtensionesVariablesAplicaciones más comunes

4.8 Asterisk CLIComandos CLI

5. Instalando Elastix5.1 Instalando desde CD5.2 Instalando Elastix sobre un soft-RAID

6. Introducción a Elastix6.1 ¿Qué es Elastix?6.2 Breve historia del proyecto

Galardones6.3 Características de Elastix

PBXFaxEmailMensajería instantánea (IM)CalendarioColaboraciónCall CenterGeneral

6.4 Licenciamiento6.5 Elastix.org: Sitio oficial del proyecto

Foros6.6 La interfaz Web de Elastix6.7 Configuración de red6.8 Sobrevuelo por la interfaz de administración Web de Elastix

Menús y módulosNavegando por la interfaz Web

Page 3: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.]

6.9 Administración de usuariosGrupos de usuariosPermisos de grupoCreación de usuarios

7. Configuración Básica de PBX7.1 Creando una extensión

Configuración de teléfono IP7.2 Configuraciones generales

Opciones del comando Dial7.3 Configuración de colas7.4 IVR y sistema de grabación

Grabación de mensaje de bienvenidaConfigurar un IVR de bienvenida

7.5 Salas de conferencias7.6 Parqueo de llamadas7.7 Música en espera7.8 Panel de Operador7.9 Funciones de transferencia de llamadas

Transferencia ciegaTransferencia atendida

8. Configuración de hardware8.1 Tipos de tarjetas y fabricantes8.2 Instalación de hardware de telefonía en Elastix8.3 Instalación física de una tarjeta

Hardware modular8.4 Detección de hardware8.5 Configuración del hardware de telefonía a nivel de Asterisk

Configuración del archivo chan_dahdi.conf8.6 Configuración de interfaces digitales utilizando los archivos de configuración DAHDI

Configuración de drivers DAHDI8.7 Detalles de DAHDI8.8 Antes de DAHDI: equipos que usaban Zaptel

Algunos cambios de nombre a tener en cuenta

9. Configuración de teléfono IP9.1 Configuración de softphone9.2 Configuración de teléfono IP

Configuración de redConfiguración de registro contra el servidor Elastix

9.3 Utilizando el Endpoint ConfiguratorConfiguración de un teléfono ATCOM, modelo AT-530Configuración de un teléfono Polycom SoundPoint IP 501Actualización por TFTPPersonalizando los archivos de configuración

10. Configuración avanzada de PBX10.1 Ruteo de llamadas

Rutas EntrantesRutas Salientes

10.2 TroncalesTroncales de tipo IAX y SIPTroncales de tipo DAHDI

Page 4: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.]

Troncales personalizadas10.3 Tarifación

Visualizar, Editar y EliminarCrear TarifaReporte de FacturaciónDistribución de DestinosConfigurar Facturación

10.4 ReportesReporte CDRUso de Canales

10.5 Configuración DISA10.6 Condiciones de tiempo

11. Funcionamiento interno de FreePBX11.1 Fundamentos de FreePBX11.2 Organización de archivos11.3 Configuración

amportal.conf11.4 retrieve_conf: Generador del plan de marcado11.5 dialparties.agi11.6 Estructura de un módulo de FreePBX

12. Conectando Servidores Elastix12.1 Interconexión entre dos servidores Elastix

Definiendo la troncal SIPDefiniendo las rutas salientes

12.2 Conexión con proveedores de llamadas vía IPDefiniendo la troncal SIPDefiniendo la ruta saliente

12.3 Conexión predefinida con proveedores de llamadas vía IP

13. Calidad de voz13.1 Síntomas de los problemas de voz

EcoBajo nivel de volumenRetardo de vozDistorsión de voz

13.2 Parámetros relacionados con la calidad de voz en redes de paquetesRetardo de redPérdida de paquetesJitter

13.3 Cómo medir la calidad de vozEscala MOSModelo E

13.4 Canceladores de ecoFuncionamiento de canceladores de ecoEl estándar G.168OSLEC

14. Protocolos VoIP al descubierto14.1 Protocolo SIP

Detalles del protocoloSeñalización SIPSIP y Asterisk

Page 5: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Indice.htm[24/11/2011 10:21:07 p.m.]

14.2 Protocolo IAXFases de una llamada IAXFrames

14.3 Protocolo RTPEstructura de un paquete RTP

14.4 Protocolo SRTP

15. Diagnóstico básico de problemas15.1 Interpretando el log

El archivo /var/log/asterisk/full¿Qué información nos puede indicar el campo MENSAJE?Número de proceso (PID)

15.2 Diagnóstico a través del CLI15.3 Sniffing

16. Control externo de Asterisk16.1 Asterisk AGI

Ejecución de scripts AGIParámetros enviados al script AGIComandos AGILibrerías AGIEjemplo sencillo de script AGI

16.2 Asterisk AMIProbando desde telnetTipo de paquetes AMIComandos o acciones AMI

Apéndice A. Archivos de configuración de Asterisk distribuidos con Elastix

Page 6: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Portada.htm[24/11/2011 10:21:11 p.m.]

Ir a índice

Comunicaciones Unificadas con Elastix

Volumen 1

Segunda Edición

Edgar Landívar

Copyright (c) 2008-2011 Edgar Landívar La presente obra se encuentra licenciada bajo los términos de la licencia Creative Commons

Page 7: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Portada.htm[24/11/2011 10:21:11 p.m.]

que se encuentra a continuación http://creativecommons.org/licenses/by-nc-nd/3.0/. Si luego deleerla todavía tiene alguna duda acerca de esta licencia, envíe una carta a Creative Commons,171 2nd Street, Suite 300, San Francisco, California, 94105, USA. Segunda Edición

A Danielita, por su sonrisa…

Reconocimiento La elaboración de este libro involucró un enorme trabajo que fue facilitado gracias a la generosa colaboración dealgunas personas con las cuales me encuentro enormemente agradecido. Mis agradecimientos más especiales a:

José Landívar y Alfredo Salas de ElastixDepot LLC, por la prolija revisión del volumen 1, párrafo a párrafo.A mi Esposa, por la comprensión durante el tiempo que le tuve que dedicar a la escritura del presente libro.A Paul Estrella, por ejercer la presión necesaria para que esta obra se termine a tiempo.A Bob Fryer por su importante ayuda revisando la versión en Inglés.

El libro online A partir de esta segunda edición el libro contará con su propio sitio Web en http://www.elastixbook.com. Desdeaquí el lector podrá acceder al libro en formato HTML.

¿Dónde adquirir este libro? La versión impresa, tanto como la versión digital, pueden ser adquiridas a través de Lulu.com. Un hipervínculo estádisponible en http://www.elastixbook.com.

Page 8: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Portada.htm[24/11/2011 10:21:11 p.m.]

Feedback Como siempre, cualquier sugerencia será bien recibida. Que el lector no dude en escribir un email [email protected]

Ir a índice

Page 9: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/Introduccion.htm[24/11/2011 10:21:12 p.m.]

Ir a índice

Introducción Muchas cosas han cambiado en Elastix desde el año 2008, cuando se publicó por primera vez la presente obra.Debo admitir eso sí que la tarea de actualizar el libro inicialmente me pareció sencilla, pero pronto me di cuentaque se trataba de un trabajo enorme. El estar inmerso día a día en el desarrollo del producto no me había hechonotar la gran cantidad de cambios ocurridos desde aquel Octubre de 2008 cuando la primera versión fue lanzada.La inicialmente “sencilla” tarea tomó 4 veces más de lo planificado, teniendo que postergar la fecha de publicaciónmás de una vez. Aquella primera edición lanzada en 2008 tuvo para mí un éxito mucho mayor al esperado. Desde el primer día tuveen mi bandeja de correo agradecimientos y sugerencias de mejoras para próximas versiones. El libro se convirtió enlibro de texto del programa oficial de entrenamiento y certificación de Elastix e inclusive ganó un premio a lasventas en Lulu.com, lo cual, tengo que admitir, me sorprendió enorme y gratamente. Pese a todo lo anterior, lo más importante que aquella primera edición me dejó fue la indescriptible satisfacciónpersonal de sentirme un escritor. Mientras lo escribía nunca pude percibir este hecho pues estaba más concentradoen que el libro fuera de utilidad a la comunidad de usuarios de Elastix. Sin embargo, luego de su publicación,cuando comencé a recibir el primer feedback de los interesados lectores, supe que había hecho algo importante, nosolo para los usuarios de Elastix, sino para mí mismo. En cuanto a los cambios producidos en esta segunda edición debo mencionar que he tratado que los capítulos de lapresente obra se mantengan fieles a la estructura original, para de esta manera facilitar la lectura a quienes yaleyeron la edición anterior. Sin embargo, mucho contenido ha sido actualizado o mejorado. Algunos capítulos hansido prácticamente reescritos, mientras que en otros los retoques son solo superficiales. No me queda más que invitarlos a explorar el fascinante mundo de las comunicaciones unificadas. Por supuesto,usando Elastix. -- Edgar LandivarElastix Project Leader

Ir a índice

Page 10: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.1_Breve_historia_telefonia.htm[24/11/2011 10:21:14 p.m.]

Ir a índice Siguiente

1Introducción a la telefonía

No importa si yo muero, otros terminarán mi trabajo…-- Mark Twain

1.1 Breve historia de la telefonía Sin duda la invención de lo que hoy conocemos como telefonía debió ser un acto asombroso en su tiempo, casimágico. El oír la voz en tiempo real de alguien ubicado en un sitio remoto saliendo de una misteriosa caja en unaépoca en la que esto era solo posible en la ciencia ficción debió haber sido una experiencia única y casi fantástica. De seguro que la idea de un aparato parlante ya rondaba por la cabeza de muchos inventores desde tiemposinmemoriales. Sin embargo, solo recién a inicios del siglo 19 fue cuando pareció algo alcanzable pues ya se habíadescubierto la electricidad, inventado el telégrafo y algunos ya experimentaban con ondas de radio.

Los albores de la telefonía A mediados del siglo 19 hubo un interesante movimiento en torno a lo que hoy conocemos como teléfono. En 1849 Antonio Meucci, médico italiano considerado por muchos como el inventor del teléfono, hizo unademostración de un dispositivo capaz de transmitir voz en La Habana, Cuba. Pocos años después, en 1854, elmismo Meucci hace una nueva demostración de su invención en la ciudad de Nueva York, USA. Mientras Meucci se las daba a las tareas de inventor, otros también perseguían la idea de construir un “telégrafoparlante” y es así como en 1860 el alemán Johann Philipp Reis construye un dispositivo capaz de transmitir voz.

Page 11: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.1_Breve_historia_telefonia.htm[24/11/2011 10:21:14 p.m.]

Este aparato estaba basado en la idea original de Charles Bourseul quien a su vez describió la construcción dedicho dispositivo en 1854 pero nunca lo construyó. Reis continuó mejorando su aparato y un año más tarde yaestaba transmitiendo voz a más de 100 metros de distancia.

Teléfono de Reis

Un par de años más tarde Innocenzo Manzetti construye el esperado “telégrafo parlante” que él mismo habíavisionado ya en 1844, pero no se interesa en patentarlo.

Los problemas con las patentes Hasta este momento en la historia ya existían algunos prototipos de teléfono pero nadie lo había patentado. El primero en tratar de patentar el invento fue Meucci, quien en 1871 suscribió un documento de “aviso de patente”pero por su condición económica nunca pudo pagar el dinero para terminar este trámite y su documento expirópocos años después. Meucci nunca pudo comercializar su invento y alcanzar la prosperidad. En 1875, un año después de expirar el trámite de patente de Meucci, Alexander Graham Bell, un escocés radicadoen los Estados Unidos, logra patentar un aparato similar y es el primero en hacerlo. Bell había estado experimentando previamente con algunas ideas para concebir su dispositivo telefónico hasta queun día logró arrancarle a la electricidad algunos sonidos. Cuenta la historia que la primera llamada que hizo fuepara decirle a su asistente las célebres frases “Mr. Watson, come here. I want to see you.” (“Sr. Watson, venga.Necesito verlo.”) Un hecho curioso que desató mucha polémica es que otro inventor llamado Elisha Gray también trató de patentarun invento similar tan solo unas pocas horas después de Bell. Los dos inventores entraron en una conocida disputalegal que finalmente ganó Bell. Gracias a la patente Bell pudo hacer de la idea del teléfono un negocio rentable y tiene el mérito de haberdesarrollado la idea y convertirla en algo práctico para la sociedad.

Page 12: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.1_Breve_historia_telefonia.htm[24/11/2011 10:21:14 p.m.]

Ilustración de dos personas hablando por teléfono a fines del siglo 19

Se cuenta que en determinado momento Bell trató de vender su patente a Western Union por $100 mil dólares peroel presidente de Western Union se negó pues consideró que el teléfono era nada más que un juguete. Tan solo dosaños más tarde el mismo directivo de Western Union le comentó a sus colegas que si pudiera conseguir la patentede Bell por $25 millones de dólares lo consideraría una ganga! Esto nos da una idea de cómo comenzaba a crecer el negocio de Bell en aquellos tiempos. En 1886, ya existíanmás de 150,000 abonados telefónicos en los Estados Unidos. A partir de ese entonces la telefonía poco a poco se empezó a convertir en un servicio básico de la sociedad actual.

El desarrollo de la tecnología telefónica Como sucede siempre con los avances tecnológicos, la telefonía continuó evolucionando. Al principio para que unabonado se comunicara con otro éste tenía que solicitarle la llamada a una operadora. Esta persona era quienconectaba manualmente los cables para conmutar un punto con el otro. En 1891 se inventó un teléfono automáticoque permitía marcar directamente. En un principio Bell fue exclusivamente la única compañía en explotar la tecnología debido a sus patentes. Sinembargo, cuando estas expiraron nacieron cientos de pequeñas compañías que empezaron a prestar este servicio, lamayoría en sitios rurales donde Bell aún no llegaba. Poco a poco estas compañías empezaron a crecer y ya ainicios del siglo 20 tenían en su conjunto más abonados que la propia Bell. La competencia hizo lo suyo y latecnología telefónica aceleró su evolución. Ya para finales de la segunda guerra mundial el servicio telefónico llegaba a millones de abonados. Cabemencionar que los abonados arrendaban el aparato teléfonico a la compañía telefónica como parte del contrato. En 1947, científicos de Bell inventan el transistor y cambian el curso de la historia de la humanidad. En 1948ganan el Premio Nobel por su trabajo. En los años sesenta se lanzan los primeros satélites de comunicaciones y las comunicaciones entre continentes sefacilitan. No está demás decir que esto no hubiera sido posible sin la previa invención del transistor. En 1982, el Departamento de Justicia de los Estados Unidos gana un juicio a AT&T (nuevo nombre de Bell) en elcual esta última acuerda desmembrar la compañía en siete compañías regionales de telefonía conocidas como

Page 13: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.1_Breve_historia_telefonia.htm[24/11/2011 10:21:14 p.m.]

Regional Bell Operating Companies (RBOCs) o “Baby Bells”. Todo esto a cambio de los derechos de ingresar enel mercado de las computadoras. A partir de ésta y otras decisiones legales, los abonados pueden comprar sus propios aparatos telefónicos lo cualtermina mermando el monopolio de AT&T. La compañía pierde mucha de su valuación y se ve en gravesproblemas financieros. Es irónico que en el 2005, AT&T terminase siendo adquirida por una de las Baby Bells,SBC Communications.

Ir a índice Siguiente

Page 14: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.2_Principio_transmision_de voz.htm[24/11/2011 10:21:16 p.m.]

Anterior Ir a índice Siguiente

1.2 Los principios de la transmisión de voz La voz humana está compuesta por ondas acústicas que viajan a través del aire a la velocidad del sonido, esto es a1,244 Km/h (o 340 m/s). Esto es más rápido que un avión comercial. Pero esta rapidez no significa que usted sepueda comunicar fácilmente con puntos distantes pues la voz humana se atenúa rápidamente, perdiendo energía amedida que viaja. Luego de unos pocos metros ya no podemos escuchar una conversación. La voz humana por tanto es de la misma naturaleza que el resto de ondas acústicas y esto ya se conocía desde antesde la invención del teléfono. Antes de la invención del teléfono también se conocía que existían otros tipos de ondas llamadas ondas eléctricasque podían ser transmitidas a través de un conductor metálico como un cable de cobre. Este segundo tipo de ondases de una naturaleza diferente a las ondas acústicas y viaja a la velocidad de la luz, es decir aproximadamente300,000 Km/s. Esto es más rápido de lo que podamos imaginar aunque para fines prácticos podemos decir queestas ondas se desplazan casi instantáneamente de un punto a otro. Otra cosa interesante es que podemos controlarla atenuación de estas ondas y hacerlas viajar grandes distancias. Con estos hechos conocidos ya a mediados del siglo 19 es más fácil comprender que muchos persiguieran la ideade transformar las ondas acústicas en ondas eléctricas para así poder luego transmitirlas a grandes distancias através de conductores metálicos. La cuestión es que había que inventar un dispositivo para hacer dichatransformación y allí estaba la clave del asunto. Este dispositivo, conocido como micrófono en nuestros días es unaparte importante de cualquier aparato telefónico.

Rango de frecuencias de la voz humana Otra característica importante de la voz humana es que las cuerdas vocales modulan la voz en un amplio espectrode frecuencias que van de graves a agudos en un rango aproximado de 200Hz a 7kHz. ¡Todo un abanico desonidos! Esto nos hace suponer que un micrófono debe ser capaz de capturar y transmitir todo este rango de frecuencias. Sinembargo, en la actualidad sabemos que para transmitir voz entendible no es necesario transmitir todas lasfrecuencias sino un rango mucho menor lo cual tiene sus ventajas pues facilita su transmisión como veremos másadelante. Por lo tanto los teléfonos comerciales solo transmiten un rango aproximado de 400Hz a 4kHz. Estodistorsiona en algo la voz aunque aún es posible entender. Es por eso que cuando oímos a alguien por teléfono suvoz suena ligeramente diferente que en la vida real pero aun así podemos entender la conversación.

El micrófono El micrófono fue un elemento clave en la invención del teléfono pues es el dispositivo que realiza la conversión delas ondas mecánicas a ondas eléctricas. Hay muchos tipos de micrófonos que operan sobre diferentes principios. Uno que se usó por mucho tiempo enteléfonos era el de carbón que consistía en una cápsula llena de granitos de carbón entre dos placas metálicas. Unade las placas era una membrana que vibraba con las ligeras presiones de las ondas de voz. De esta manera laresistencia eléctrica de la cápsula variaba con la voz y se generaba una señal eléctrica correspondiente.

Page 15: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.2_Principio_transmision_de voz.htm[24/11/2011 10:21:16 p.m.]

Micrófono de carbón extraído de teléfono de disco

Otro tipo de micrófono muy común en la actualidad es el dinámico o electro-magnético que consiste en una bobinade hilo de cobre enrollada sobre un núcleo de material ferromagnético. Este núcleo se encuentra sujetado a undiafragma que vibra con la presión de las ondas de voz. De esta manera se induce una ligera corriente eléctrica enla bobina que es amplificada luego al interior del teléfono.

Diagrama esquemático de micrófono electro-magnético

Ancho de banda y capacidad de información Ancho de banda puede ser un término difícil de entender al principio pues es un concepto bastante amplio. En general podemos decir que ancho de banda es una medida de la cantidad de información que podemostransmitir por un medio por unidad de tiempo. Debido a que es una medida por unidad de tiempo muchas veces sehace una analogía con la velocidad. Pero hay que estar atento a confusiones. Medidas comunes para expresar el ancho de banda son los bits por segundo. Esta medida se puede abreviar comobits/s, bps o baudios.

Page 16: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.2_Principio_transmision_de voz.htm[24/11/2011 10:21:16 p.m.]

El ancho de banda es un término muy importante cuando se habla de telefonía pues las comunicaciones en tiemporeal necesitan un ancho de banda mínimo asegurado para entregar una comunicación de calidad en su destino.

Anterior Ir a índice Siguiente

Page 17: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.3_Digitalizacio_voz.htm[24/11/2011 10:21:17 p.m.]

Anterior Ir a índice Siguiente

1.3 Digitalización de la voz Las redes digitales de transmisión de voz y datos son comunes en nuestra era. Fueron creadas ya que presentanciertas ventajas sobre las redes analógicas como por ejemplo que conservan la señal casi inalterable a través de surecorrido. Es decir, es más difícil que la comunicación se vea afectada por factores externos como el ruidoeléctrico. Además nos provee de métodos para verificar periódicamente la integridad de la señal, entre otrasventajas. Dicho fácil, digitalizar una señal de voz no es otra cosa que tomar muestras (a intervalos de tiempo regulares) de laamplitud de la señal analógica y transformar esta información a binario (1s y 0s). Este proceso de denominamuestreo.

Teorema de Nyquist En 1928 Henry Nyquist, un ingeniero Suizo que trabajaba para AT&T, resolvió el dilema del número mínimo demuestras necesarias para poder reconstruir una onda a su forma original. El teorema propuesto dice que la frecuencia de muestreo debe ser como mínimo el doble de ancho de banda. Estoqueda reflejado de mejor manera con la siguiente expresión.

fm ≥ 2 BWs Hagamos un breve cálculo acerca de cual sería la frecuencia de muestreo para poder convertir una señal de vozhumana (análoga) a digital y luego poder reconstruirla en el destino. Ya habíamos dicho que para que la voz humana sea entendible es suficiente transmitir un rango de frecuencias deentre 400Hz a 4kHz. Por lo tanto, según el teorema de Nyquist deberíamos muestrear al doble de la frecuenciamayor como mínimo, es decir a 8kHz. Más adelante veremos que precisamente esta frecuencia de muestreo de 8,000Hz es la que se usa en la mayoría decodecs. ¡Gracias Nyquist!

Anterior Ir a índice Siguiente

Page 18: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.4_Redes_orientadas_a_circuitos.htm[24/11/2011 10:21:18 p.m.]

Anterior Ir a índice Siguiente

1.4 Redes orientadas a circuitos Las redes orientadas a circuitos (circuit switched) son aquellas donde se establece un circuito exclusivo o dedicadoentre los nodos antes de que los usuarios se puedan comunicar. Una vez que se establece un circuito entre dos puntos que quieren comunicarse, el resultado básicamente es elequivalente a conectar físicamente un par de cables de un extremo a otro. El circuito es exclusivamente reservadopara uso de una conversación y no puede ser usado por otros. En cada circuito el retardo es constante, lo cual es una ventaja. Sin embargo, este tipo de redes es costoso debido almismo hecho de que se necesita un circuito dedicado para las conversaciones de cada abonado. Este tipo de redes es el tradicionalmente usado hoy en día por compañías telefónicas alrededor del mundo y es elmismo que usó Bell en sus inicios; obviamente guardando las distancias tecnológicas correspondientes. Es común que ciertas personas confundan las redes de circuitos con las redes analógicas pero es necesario aclararque las redes de circuitos bien pueden transportar datos digitalmente.

Anterior Ir a índice Siguiente

Page 19: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.5_Redes_orientadas_a_paquetes.htm[24/11/2011 10:21:19 p.m.]

Anterior Ir a índice Siguiente

1.5 Redes orientadas a paquetes Las redes orientadas a paquetes (packet switched) son aquellas en las que se transmiten simultáneamente diferentesflujos de información en un mismo medio. Para hacer esto, se divide el tráfico de cada flujo de información enfragmentos o paquetes que se envían intercaladamente. Luego, en el destino los paquetes se reensamblan parareproducir el mensaje original.

Simulación gráfica de envío de información en una red orientada a paquetes

Un ejemplo de este tipo de redes son las redes IP como es el caso del Internet, donde por una misma conexiónpueden transmitirse distintos flujos de información. De esta manera podemos atender una video-conferencia almismo tiempo que enviamos un correo electrónico o navegamos por el Web. Inclusive por este tipo de redespueden circular simultáneamente flujos de información para diferentes destinos o direcciones IP. A diferencia de las redes orientadas a circuitos, en este tipo de redes el ancho de banda no es fijo ya que dependedel tráfico de la red en un momento dado. Adicionalmente, cada paquete de un mismo flujo de información no estáobligado a seguir el mismo camino para llegar a su destino. Debido a esto, los paquetes que originalmente fuerongenerados en secuencia pueden llegar desordenados a su destino. Este tipo de factores son muy importantes a teneren cuenta cuando se trafica voz sobre una red de paquetes ya que afectan la calidad de la llamada. Las redes de paquetes se han vuelto populares, principalmente porque optimizan recursos debido al hecho de poderutilizar el mismo medio para enviar varios flujos de información..

Anterior Ir a índice Siguiente

Page 20: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.6_Red_Publica_Telefonica.htm[24/11/2011 10:21:20 p.m.]

Anterior Ir a índice Siguiente

1.6 Red Pública Telefónica (PSTN) La Red Pública Telefónica o PSTN (por sus siglas en inglés) es esencialmente una red basada en circuitos. Esta redcubre tanto telefonía fija como móvil y es quien hace posible que podamos comunicarnos con cualquier persona ennuestra ciudad o alrededor del mundo. Originalmente fue una red analógica aunque actualmente es una red digital en su mayor parte. Es importanterevisar los dos tipos de circuitos: analógicos y digitales.

Anterior Ir a índice Siguiente

Page 21: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.7_Circuitos analogicos.htm[24/11/2011 10:21:24 p.m.]

Anterior Ir a índice Siguiente

1.7 Circuitos analógicos Los circuitos analógicos son comúnmente pares de cobre que llegan a los abonados del servicio telefónico y pordonde se transmite la señal eléctrica de la voz de manera analógica. El mismo circuito lleva adicionalmente laseñalización necesaria para establecer, mantener y terminar una llamada. Estos circuitos analógicos se debenconectar a un switch telefónico encargado de direccionar la comunicación entre los abonados. Actualmente, los circuitos analógicos están en decadencia pues las compañías telefónicas encontraron muchasventajas en las comunicaciones digitales. Por esta razón, pese a que en la actualidad aún vemos circuitosanalógicos esto se trata tan solo de la última milla. En cierto punto de la red telefónica esta comunicación seconvierte a digital y es transmitida a un switch telefónico digital. Los circuitos analógicos se asocian comúnmente con el término de “telefonía tradicional”. Debido a que originalmente era más común que los teléfonos estuvieran ubicados en áreas rurales donde no llegabala electricidad se decidió que la red telefónica proveyera cierto voltaje de alimentación. Es por esto que algunosmodelos de teléfonos analógicos no necesitan conectarse a la alimentación eléctrica. En todo caso la Oficina Central (OC) genera 48 Voltios de corriente directa para alimentar a los teléfonos de losabonados. Usando léxico estricto deberíamos decir -48 Voltios debido a que este voltaje se mide con respecto auno de los conductores. Sin embargo para ser prácticos en este libro usaremos indistintamente 48V o -48V parareferirnos a lo mismo.

Señalización analógica Para que las llamadas telefónicas funcionen correctamente es necesario contar con indicaciones o señales eléctricasque nos permitan intercambiar información entre el abonado y la OC. En breve veremos en qué consisten lasseñales más comunes. Existen básicamente tres métodos de señalización analógica que la industria ha desarrollado a través de los años.Estos se llaman loop start, ground start y kewlstart. Es importante cuando se configura una central telefónica queva conectada a una línea analógica que escojamos el método de señalización adecuado pues caso contrariopodemos encontrarnos con problemas extraños como que la línea se cuelga inesperadamente o que no podemoscolgar la línea correctamente, entre otras cosas. La diferencia entre loop start y ground start radica en la manera en la que el teléfono requiere tono de marcado ala OC (proceso también llamado seizure). Ground start requiere tono de marcado aterrizando (de allí el términoground) uno de los conductores de la línea telefónica mientras que loop start lo hace realizando un corto circuitoentre ambos conductores (es decir creando un lazo o loop). Kewlstart es una evolución de loop start que le añade un poco más de inteligencia a la detección de desconexiones(colgado de la llamada) pero básicamente sigue siendo un loop start. Debido a que ground start no es muy común en nuestros días, casi siempre nos veremos usando loop start.

Page 22: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.7_Circuitos analogicos.htm[24/11/2011 10:21:24 p.m.]

A continuación explicaremos más detalladamente la señalización analógica para los eventos más comunes. Parahacerlo nos basaremos en el progreso de una llamada típica usando señalización loop start. El progreso de unallamada lo podemos dividir en seis instancias: colgado (on-hook), descolgado, marcación, conmutación, ringado yconversación.

Colgado Mientras el teléfono está colgado la OC provee un voltaje DC de 48 Voltios. El teléfono mantiene un circuitoabierto con la línea telefónica; es decir que actúa como si no estuviera conectado y por lo tanto no fluye corrientepor la línea. Este estado también es conocido como on-hook por su significado en inglés.

Descolgado Cuando el usuario descuelga el auricular el teléfono envía una señal a la OC. Esta señal consiste en cerrar elcircuito. Es decir, internamente el teléfono conecta entre sí los dos cables de la línea telefónica a través de unaresistencia eléctrica. Apenas la OC se da cuenta de esto envía tono de marcado al teléfono. Este tono de marcado le indica al abonadoque ya puede marcar el número. En gran parte de América el tono de marcado consiste en dos ondas senoidales enviadas simultáneamente. Estasondas son de 350 Hz y 440 Hz. En Europa el tono de marcado consiste en una sola onda de 425 Hz. Sin embargohay países en los que estos valores podrían ser diferentes.

Nota: Cuando era adolescente acostumbrábamos a afinar la guitarra escuchando el tono de marcado delteléfono pues resulta que 440 Hz es la frecuencia de la nota musical LA (A) que corresponde a la quintacuerda de la guitarra.

Marcación La marcación puede ser por pulsos o por tonos. Los pulsos ya casi no se usan y fueron populares en los tiempos delos teléfonos de disco. Los tonos son pares de frecuencias asociadas con los dígitos telefónicos. Estas frecuencias setransmiten hasta la OC quien traduce estos tonos a números. Más adelante se explicará más de estos tonos bajo el título DTMFs.

Conmutación Una vez recibido los dígitos, la OC tratará de asociar este número marcado con el circuito de un abonado. En casode que el destinatario no fuere un abonado local, enviará la llamada a otro switch telefónico para su terminación. Cabe resaltar que la conmutación hoy en día es completamente automática a diferencia del pasado cuando eratrabajo de la operadora.

Page 23: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.7_Circuitos analogicos.htm[24/11/2011 10:21:24 p.m.]

Ringado o Timbrado Una vez que la OC encuentra al abonado destinatario tratará de timbrarlo (ringing). La señal de ring es una ondasenoidal de 20 Hz y de 90 Voltios de amplitud.

Nota: Si hemos sido observadores nos habremos dado cuenta de que la señal de ring tiene una amplitudconsiderable de 90 Voltios. Además recordemos que la línea ya tiene un componente adicional de VoltajeDC de 48 Voltios. Es por esta razón que si manipulamos los cables telefónicos desnudos en el precisomomento en el que llega una señal de ring podemos recibir una pequeña descarga eléctrica y pasar unbuen susto.

Adicionalmente a la señal de ring que la OC envía al destinatario también envía una notificación a quien originó lallamada. Este tono audible recibe el nombre de ring-back y consiste en dos ondas senoidales superpuestas de 440Hz y 480 Hz. Estas ondas van intercaladas con espacios de silencio. En caso de que el destinatario se encuentre ya en una llamada activa entonces en lugar del ring-back se devuelveun tono de ocupado (busy) a quien originó la llamada. Este tono de ocupado consiste en dos ondas sinusoidalessuperpuestas de 480 Hz y 620 Hz intercaladas con espacios de silencio de medio segundo. Todos los lectores sin duda han escuchado un ring-back y un tono de ocupado (busy) alguna vez en sus vidas.

Conversación Si el destinatario decide contestar la llamada el teléfono cerrará el circuito telefónico (de la misma manera queocurrió con el teléfono que originó la llamada en la etapa de descolgado). Esta señal le informará a la OC que eldestinatario decidió contestar y completará la conexión. La llamada telefónica está finalmente en curso.

DTMFs Muchas veces es necesario enviar dígitos a través de la línea telefónica tanto para marcar como en medio de unaconversación. Con esta finalidad se pensaron los DTMFs. DTMF es un acrónimo de Dual-Tone Multi-Frequency.Es decir que cada DTMF es en realidad dos tonos mezclados enviados simultáneamente por la línea telefónica.Esto se hace así para disminuir los errores. A continuación una tabla ilustrando los pares de frecuencias para cada dígito. 1209 Hz 1336 Hz 1477 Hz 1633 Hz697 Hz 1 2 3 A770 Hz 4 5 6 B852 Hz 7 8 9 C941 Hz * 0 # D

Como se puede ver en la tabla también hay correspondencias para los signos * y # así como también para loscaracteres A, B, C y D.

El teléfono analógico

Page 24: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.7_Circuitos analogicos.htm[24/11/2011 10:21:24 p.m.]

Es importante hablar de este componente importante de la red telefónica pues recordemos que su invención fue loque marcó el desarrollo del negocio de la telefonía. El teléfono analógico todavía es el tipo de teléfono más común en el planeta y la comprensión de sufuncionamiento nos permitirá entender más adelante algunos conceptos clave como por ejemplo el eco. En realidad el teléfono analógico, en su forma más básica, es un dispositivo sencillo compuesto de unos cuantoscomponentes. • Auricular• Micrófono• Switch para colgado/descolgado• Convertidor de dos a cuatro hilos (también llamado híbrido)• Marcador (dialer)• Campana o dispositivo de timbrado

Diagrama de componentes de un teléfono analógico

La mayoría de los componentes se explican por si solos. Sin embargo algunos lectores se preguntarán de qué setrata el convertidor de 2 a 4 hilos también conocido como híbrido.

Convertidor de 2 a 4 hilos Un componente importante de un teléfono analógico es el convertidor de 2 a 4 hilos, conocido también comodispositivo 2H/4H, bobina híbrida o simplemente híbrido. Este dispositivo es necesario para separar la señal deaudio de ida de la de regreso ya que son dos los participantes en una conversación y solo existe un par de cables.Si existieran tres o cuatro cables (2 de ida y 2 de venida) el convertidor de 2 a 4 hilos no fuera necesario, pero estoprobablemente incrementaría los costos de cableado y las compañías telefónicas prefieren lidiar con los problemasde acoplamiento que este convertidor introduce en lugar de incrementar sus costos. En general no existe convertidor de 2 a 4 hilos perfecto ya que es muy difícil separar las señales de ida y deregreso completamente. Es por eso que este dispositivo históricamente ha sido una de las causas de eco en líneastelefónicas mal acopladas. Ya hablaremos más de esto en el capítulo Calidad de voz.

Page 25: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.7_Circuitos analogicos.htm[24/11/2011 10:21:24 p.m.]

Anterior Ir a índice Siguiente

Page 26: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.8_Circuitos digitales.htm[24/11/2011 10:21:25 p.m.]

Anterior Ir a índice Siguiente

1.8 Circuitos digitales La PSTN también sirve a sus abonados con circuitos digitales. Estos circuitos ofrecen la ventaja de podermultiplexar más de una línea en el mismo medio por lo que resulta atractivo para abonados con necesidades de ungran número de líneas telefónicas, por lo general empresas.

La base DS-0 Para decirlo simple, DS-0 es un canal digital de 64Kbit/s. Un DS-0 es por tanto una medida de canal estándar ounidad que nos sirve para definir múltiplos mayores como los circuitos que veremos a continuación.

Circuitos T-carrier y E-carrier Los circuitos T-carrier (o portadora-T) fueron diseñados como nomenclatura para circuitos digitales mutiplexadosy fueron desarrollados por Bell Labs hace más de cincuenta años. Los circuitos E-carrier son la equivalenteeuropea. El más conocido de los circuitos T-carrier es el popular T1 (y su contraparte E1). Un T1 es un circuito digitalcompuesto de 24 DS-0´s mientras que un E1 está compuesto por 32 DS-0´s. Si hacemos las matemáticas notaremosque un T1 trafica 1.544 Mbit/s mientras que un E1 trafica 2.048 Mbit/s. Existen múltiplos mayores de T1 como T2, T3, y T4, los que se relacionan en la siguiente proporción.

1 T4 = 6 T3 = 42 T2 = 168 T1

SONET y Circuitos Ópticos SONET (Synchronous optical networking) fue desarrollado con el objetivo de contar con una nomenclatura similara las T-carrier pero usando la tecnología de fibra óptica. SONET utiliza múltiplos de T3 para sus anchos de banday su circuito base es el llamado OC-1 equivalente a 1 T3. Existen múltiplos mayores de OC-1 como OC-3, OC-12, OC-24, OC-48, entre otros.

Anterior Ir a índice Siguiente

Page 27: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.9_Protocolos_Senalizacion_Digital.htm[24/11/2011 10:21:26 p.m.]

Anterior Ir a índice Siguiente

1.9 Protocolos de Señalización Digital Los protocolos de señalización se utilizan para transmitir información de estado del canal de comunicaciones(como “desconectado”, “timbrando”, “respondido”), información de control y otra información como DTMFs,caller ID, entre otros. Estos protocolos se pueden agrupar en dos tipos llamados Señalización Asociada al Canal (CAS, por el acrónimoen Inglés) y Señalización de Canal Común (CCS, por el acrónimo en Inglés). La diferencia es que mientras CAStransmite la señalización en el mismo canal en que viaja la información, CCS la transmite en un canal separado. Espor esto que con CAS se reduce ligeramente el ancho de banda disponible para la comunicación ya que una partede él se está usando para señalización. Esa es una de las razones por las cuales las compañías telefónicas hanadoptado en su mayoría CCS.

Nota: No confunda el lector CAS y CCS con protocolos de señalización. Tan solo son tipos de protocolosque se explican aquí para hacer más fácil la categorización o agrupación de los mismos.

Señalización Asociada al Canal (CAS) El protocolo de tipo CAS más conocido es robbed-bit y es usado en circuitos T1 y E1 alrededor del mundo. Robbed-bit toma (o “roba”, de allí su nombre) el octavo bit de cada canal de comunicación cada seis frames y loreemplaza por información de señalización. El bit original robado simplemente se pierde.

Nota: Como ejemplo para el lector, cada frame T1 consiste de 193 bits, 8 bits por cada uno de los 24canales más 1 bit de framing.

Hay que notar de lo anterior que esto es posible debido a que la voz no es muy sensible a la pérdida de ese bit deinformación ya que es el bit menos significativo. Sin embargo, cuando transportamos data (al contrario de la voz)la pérdida de un bit no puede pasar desapercibida y la calidad de la transmisión se degrada de manera sensible. Otro protocolo de tipo CAS que aún subsiste en nuestros días es R2. Se trata de un protocolo que fue popular enlos años sesenta. En realidad R2 es una familia de protocolos donde cada implementación se denomina variante.Existen variantes dependiendo del país o inclusive de la compañía telefónica que lo ofrece.

Nota: Antes de la versión 1.6 Elastix soportaba el protocolo R2 utilizando la librería Unicall(http://www.soft-switch.org/unicall/installing-mfcr2.html), pero a partir de la versión 1.6 el soporte fuecambiado para utilizar la implementación del proyecto openR2 desarrollado por Moisés Silva(www.libopenr2.org).

Señalización de Canal Común (CCS) El mejor ejemplo de protocolo de tipo CCS es el Integrated Services Digital Network (ISDN). Este protocolo nos permite transmitir voz y datos simultáneamente sobre pares telefónicos de cobre con calidad

Page 28: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_1/1.9_Protocolos_Senalizacion_Digital.htm[24/11/2011 10:21:26 p.m.]

superior a las líneas telefónicas analógicas. El objetivo de ISDN fue el de facilitar las conexiones digitales para poder ofrecer una amplia gama de serviciosintegrados a los usuarios. ISDN establece dos tipos de interfaces para cumplir con este fin.

BRI: Basic Rate InterfacePRI: Primary Rate Interface

Un BRI supone 2 canales útiles (también llamados canales B) de 64Kbit/s cada uno, más un canal de señalizaciónde 16Kbit/s (también llamado canal D) que en total suman 144Kbit/s. BRI estaba llamado a ser un estándar popular en hogares pero no fue así del todo y tuvo muy poca acogida en estesegmento del mercado en los Estados Unidos. En Europa la situación fue diferente y actualmente es utilizado enmuchos países de este continente. PRI es la opción ideal para usuarios de mayor envergadura como negocios o empresas pues puede aglutinar máscanales B. Actualmente es muy popular y se transmite sobre circuitos T-carrier y E-carrier.

Anterior Ir a índice Siguiente

Page 29: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.1_VoIP_sopa_de protocolos.htm[24/11/2011 10:21:28 p.m.]

Anterior Ir a índice Siguiente

2Introducción a la VoIP

Yo no hice nada por accidente, ni tampoco fueron así mis invenciones; ellas vinieron por el trabajo-- Thomas Edison

La voz sobre IP o VoIP consiste en transmitir voz sobre protocolo IP. Dicho así puede sonar simple pero las redes IP fueron diseñadas principalmente para datos y muchas de las ventajasde las redes IP para los datos resultan ser una desventaja para la voz. Esto se debe a que la voz es muy sensible aretardos y problemas de transmisión por muy pequeños que estos sean. Transmitir voz sobre protocolo IP es entonces toda una empresa con muchos problemas técnicos que resolver. Porsuerte la tecnología ha evolucionado y la pericia de algunos ingenieros talentosos ha resultado en que podamosabstraernos en gran medida de aquellos problemas inherentes a las redes IP que perjudican la calidad de voz. La evolución de la calidad de las comunicaciones de voz sobre IP en los últimos años ha sido realmentesorprendente. Actualmente podemos decir que la transmisión de voz por Internet ya es una alternativa rentable alalance de la mayoría de nosotros.

2.1 VoIP: una sopa de protocolos Hay muchos protocolos involucrados en la transmisión de voz sobre IP. Ya de por sí hay protocolos de redinvolucrados como el propio protocolo IP y otros protocolos de transporte como TCP o UDP. Encima de ellos secolocan los protocolos de señalización de voz. Como si esto fuera poco existen además muchas opciones deprotocolos de señalización disponibles lo que puede hacer que todo suene un poco confuso al principio.

Page 30: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.1_VoIP_sopa_de protocolos.htm[24/11/2011 10:21:28 p.m.]

Sopa de protocolos VoIP

Clasificando los protocolos VoIP Para simplificar las cosas podríamos clasificar a los protocolos utilizados en la VoIP en tres grupos: protocolos deseñalización, de transporte de voz y de plataforma IP.

Protocolos de señalización Los protocolos de señalización en VoIP cumplen funciones similares a sus homólogos en la telefonía tradicional,es decir tareas de establecimiento de sesión, control del progreso de la llamada, entre otras. Estos protocolos seencuentran en la capa de sesión (capa 5) del modelo OSI. Existen algunos protocolos de señalización, que han sido desarrollados por diferentes fabricantes u organismoscomo la ITU o el IETF, y que se encuentran soportados por Asterisk. Algunos son:

SIPIAXH.323MGCPSCCP

Entre estos los más populares en el ámbito de Asterisk son SIP e IAX. Más adelante en este libro entraremos en más detalles acerca del protocolo SIP.

Protocolos de transporte de voz No se debe confundir los protocolos de transporte de voz con protocolos de transporte de bajo nivel como TCP yUDP. Nos referimos aquí al protocolo que transporta la voz propiamente dicha o lo que comúnmente se denomina

Page 31: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.1_VoIP_sopa_de protocolos.htm[24/11/2011 10:21:28 p.m.]

carga útil. Este protocolo se llama RTP (Real-time Transport Protocol) y su función es simple: transportar la vozcon el menor retraso posible. Este protocolo entra a funcionar una vez que el protocolo de señalización ha establecido la llamada entre losparticipantes.

Protocolos de plataforma IP En esta categoría agruparemos a los protocolos básicos en redes IP y que forman la base sobre la cual se añaden losprotocolos de voz anteriores. En estos protocolos podríamos mencionar a Ethernet, IP, TCP y UDP.

Nota: En el presente capítulo pondremos énfasis en explicar este grupo de protocolos con el objetivo denivelar a quienes no tengan conocimientos sólidos en Networking. Sin embargo, los otros grupos deprotocolos se revisarán con más detalle en un capítulo especial dedicado a este fin.

Protocolos involucrados en una llamada SIP. El caso de IAX es muy similar.

En la figura anterior podemos observar un hecho curioso y es que pese a que SIP soporta tanto UDP como TCPsólo lo vemos posado sobre UDP. No se trata de un error sino más bien que en Asterisk la implementación de SIPsolo está disponible para UDP.

Anterior Ir a índice Siguiente

Page 32: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.2_Protocolo_IP.htm[24/11/2011 10:21:29 p.m.]

Anterior Ir a índice Siguiente

2.2 Protocolo IP El protocolo IP sin duda es uno de los más populares jamás implementados, principalmente por el auge de la granred de redes llamada Internet, que utiliza este protocolo para su enrutamiento. Por esta razón, antes de entrar endetalles acerca del protocolo IP emplearemos un par de párrafos para resumir los orígenes del Internet.

El Internet El Internet tuvo su origen en la década del sesenta como un proyecto del Departamento de Defensa de los EstadosUnidos con el objetivo de crear una red robusta que conectara algunos organismos públicos con universidades. Laidea de la red, que originalmente se llamó ARPANet, era que si alguno de los nodos quedaba fuera defuncionamiento esto no perjudicara significativamente a la red. Para esto se ideó una red descentralizada quepudiera manejar más de un camino entre dos de sus puntos. En resumen, se trataba de construir una red a prueba defallos (recordemos también que eran épocas de la Guerra Fría) y de bajo coste. Gracias a este enfoque ARPANet evolucionó hasta lo que hoy en día conocemos como Internet, una red decomunicaciones tan grande y poderosa que sin duda ha ejercido un impacto en nuestras culturas. Sin su existenciael proyecto Elastix no hubiera existido y no estarían leyendo esto ahora.

¿Qué es el protocolo IP? El protocolo IP (Internet Protocol) trabaja a nivel de red donde la información se envía en paquetes llamadospaquetes IP. Este protocolo ofrece un servicio sin garantías también llamado de mejor esfuerzo. Es decir que nadagarantiza que los paquetes lleguen a su destino, aunque se hará lo posible por hacerlos llegar.

Dirección IP Una dirección IP es un número único que provee además información de cómo ubicar al equipo que la posee. Paraque este número sea único existe una autoridad que controla la asignación de direcciones IP llamada IANA(Internet Assigned Numbers Authority). Este número único es binario y consta de 32 bits. Sin embargo, para fines prácticos y hacer que este número seamás entendible para los humanos casi siempre se representa en un formato de 4 números decimales separados porpuntos. Cada uno de estos cuatro números decimales puede tomar un valor de 0 a 255. Un ejemplo de dirección IPes 172.16.254.1

Traducción de notación decimal a binaria (32 bits) de una dirección IP

Page 33: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.2_Protocolo_IP.htm[24/11/2011 10:21:29 p.m.]

Paquete IP Como habíamos dicho antes, el protocolo IP es un protocolo que divide la información en paquetes que envía a sudestino. La ventaja de tener la información paquetizada es que estos paquetes pueden tomar diferentes caminospara llegar a destino. Es decir que hay redundancia de caminos y es menos probable que todos los paquetes sepierdan. Algunos lectores se preguntarán ¿cómo lucen los famosos paquetes? El formato de un paquete IP está diseñado para llevar información que permita diseccionarlo a su destino yobviamente que permita re-ensamblar los paquetes en el destino para recuperar la información útil. A continuaciónuna figura con una cabecera de paquete IP.

Cabecera de un paquete IP

Direccionamiento IP El direccionamiento o enrutamiento permite determinar la ruta óptima para que un paquete IP llegue su destino.Para saber dónde quiere llegar un paquete dado, hay que examinar la dirección IP de destino en el campoDestination Address de la cabecera de un paquete IP. Los equipos que se encargan de enrutar los paquetes a su destino se llaman ruteadores y básicamente contienentablas de rutas con información sobre cómo alcanzar otras redes. Por tanto, una vez que llega un paquete a unruteador éste examina la dirección IP de destino y trata de determinar a qué red pertenece esa dirección IP. Determinar la red donde quiere llegar un paquete dado no es muy difícil puesto que esa información es parte de ladirección IP. Esto es porque cada dirección IP se podría dividir en dos partes: una parte que identifica a la red yotra que identifica al equipo (también llamado host). Identificar cada una de estas partes no es tan trivial pues existen redes de diferentes tamaños y el número de bitsque corresponden a la red y al host varían respectivamente. La solución es un parámetro adicional llamado máscarade red.

Máscara de red y cálculo de dirección de red Veamos entonces cómo se obtiene la información sobre la red a la cual pertenece una dirección IP para que un

Page 34: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.2_Protocolo_IP.htm[24/11/2011 10:21:29 p.m.]

ruteador pueda encaminar correctamente un paquete a su destino. La máscara de red es un número de 32 bits al igual que una dirección IP. Se llama máscara porque si se superponea la dirección IP nos permite identificar cuál parte es la que corresponde a la dirección de red y cuál a la direccióndel host. Imaginemos que tenemos la dirección IP 130.5.5.26 con máscara 255.255.255.0. Para ilustrar cómoaplicar la máscara sobre la dirección IP convirtamos estos datos a binario como lo muestra el diagrama acontinuación.

Aplicación de máscara para obtener información de la red y host

Ahora podemos ver con más claridad que los números uno (1) en la máscara marcan el límite entre la parte de lared y la parte del host por lo tanto la dirección de red es (en binario):

10000010.00000101.00000101.00000000 Todos los números binarios a la derecha de la parte de red en la máscara se completan con ceros. Convirtamosahora la dirección de red anterior a decimal. Veamos qué obtenemos:

10000010.00000101.00000101.00000000 130.5.5.0 Lo que quiere decir que la dirección IP 130.5.5.26 pertenece a la red 130.5.5.0.Ahora el ruteador ya puede decidir hacia qué red enviar nuestro paquete IP.

Anterior Ir a índice Siguiente

Page 35: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.3_Protocolos_transporte.htm[24/11/2011 10:21:34 p.m.]

Anterior Ir a índice Siguiente

2.3 Protocolos de transporte

Nota: No se debe confundir estos protocolos con el “protocolo de transporte de voz” RTP. RTP es unprotocolo más especializado que incluso se monta sobre UDP (un protocolo que será explicado aquí). Losprotocolos de transporte aquí cubiertos son de propósito general y reposan directamente sobre el protocoloIP.

Protocolo TCP Como ya habíamos dicho el protocolo IP no garantiza que los datos lleguen a destino. Solo hace su mejor esfuerzopara que lleguen. Debido a esto es necesario un protocolo que se encargue de controlar la transmisión de datos y por esta razón sediseñó lo que se llama Transmission Control Protocol o simplemente TCP. Este es un protocolo de transporte quese transmite sobre IP. TCP ayuda controlando que los datos transmitidos se encuentren libre de errores y sean recibidos por lasaplicaciones en el mismo orden en que fueron enviados. Si se pierden datos en el camino, TCP introducemecanismos para que estos datos sean reenviados. Obviamente esto implica una carga extra de información en el flujo de datos ya que hay que enviar información decontrol adicional. Es por esto que TCP es un buen protocolo para control de sesiones pero no tan bueno para latransmisión de información en tiempo real como la voz. Sin embargo, TCP juega un rol muy importante en muchosprotocolos relacionados con un servidor Elastix. TCP es quien introduce el concepto de puerto que no es otra cosa que una abstracción para poder relacionar losflujos de datos con servicios de red específicos (o protocolos de más alto nivel). Por ejemplo, el puerto 80 se asociacon el servicio de Web o el protocolo HTTP, mientras que el puerto 25 se asocia con el servicio de correoelectrónico o protocolo SMTP.

Protocolo UDP UDP (User Datagram Protocol) es otro protocolo de transporte. Se diferencia con TCP en que a este protocolo nole importa si los datos llegan con errores o no y tampoco le importa si llegan en secuencia. La pregunta entonces es¿para qué sirve este protocolo? Bueno, un protocolo de transporte no necesariamente tiene que garantizar que la información llegue a destino ollegue en secuencia. Esta es solo una característica extra. Es más o menos análogo a un servicio de transporte demercancía. Imaginémonos una flota de motocicletas que ofrece el servicio de transporte en una ciudad eimaginémonos que le encomendamos a dicha flota la tarea de transportar un gran cargamento de archivos de unaoficina u otra. La compañía se encargará de dividir nuestro cargamento de archivos y distribuirlo en cantidades opaquetes que puedan ser transportados en sus vehículos. La flota hará lo necesario para que nuestro cargamentollegue a su destino. Esto es en esencia el servicio de transporte. Sin embargo podemos escoger dos clases deservicio: una que garantiza que la mercancía llegue segura y otra que no. Estos dos tipos de servicio son análogos alos dos tipos de protocolos de transporte que estamos describiendo en este apartado UDP y TCP.

Page 36: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.3_Protocolos_transporte.htm[24/11/2011 10:21:34 p.m.]

En fin, UDP divide la información en paquetes, también llamados datagramas, para ser transportados dentro de lospaquetes IP a su destino. Al no ser necesario incluir mucha información de control, el protocolo UDP reduce la cantidad de informaciónnecesaria en los paquetes por lo que es un protocolo más rápido que TCP. Esto lo hace adecuado para transmisiónde información que debe ser transmitida en tiempo real como la voz. Es por esta razón que la voz en aplicaciones de VoIP es transmitida sobre este protocolo.

Anterior Ir a índice Siguiente

Page 37: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.4_Codificacion_de_la_voz.htm[24/11/2011 10:21:34 p.m.]

Anterior Ir a índice Siguiente

2.4 Codificación de la voz Ya tenemos claro que para transportar la voz se utilizan algunos protocolos como SIP, IAX y otros como RTP oRTCP. Pero la voz es una onda analógica que necesita transformarse a digital en algún formato antes de sertransmitida. Lógicamente podríamos tratar de transmitirla tal cual resulta de la conversión analógica-digital (conocida comoAnalog-to-Digital Conversion, o ADC) pero resulta que nos encontramos en una red de paquetes así que debemospaquetizar esta información. Además existe la oportunidad de comprimir el resultado de la conversión ADC conalgún algoritmo para no desperdiciar recursos de la red. La búsqueda de un formato de compresión óptimo generó algunas alternativas de formatos de transmisión llamadascodecs.

Nota: Los codecs realmente no son exclusivos de la VoIP pues también se usan en otros tipos decomunicaciones digitales.

Codecs La palabra codec proviene de abreviar las palabras codificación y decodificación. Su función principal es la deadaptar la información digital de la voz para obtener algún beneficio. Este beneficio en muchos casos es lacompresión de la voz de tal manera que podamos utilizar menos ancho de banda del necesario. Algunos codecs soportados por Asterisk y comúnmente usados en comunicaciones de VoIP son G.711, G.722,G.729, GSM, iLBC, entre otros. Revisemos brevemente cuatro de ellos: G.711, G.722, G.729 y GSM.

G.711 G.711 es uno de los codecs más usados de todos los tiempos y proviene de un estándar ITU-T que fue liberado en1972. Viene en dos sabores llamados u-law y a-law. La primera versión se utiliza en los Estados Unidos y lasegunda se utiliza en Europa. Una de sus características es la calidad de voz debido a que casi no la comprime. Utiliza un muestreo de 8 bits a8kHz resultando en 64kbit/s. Es el codec recomendado para redes LAN pero hay que pensarlo dos veces antes deutilizarlo en enlaces remotos debido al alto consumo de ancho de banda. El soporte para este codec viene habilitado por defecto en Elastix.

G.722 G.722 ofrece una taza de muestreo de 14 bits a 16 kHz, es decir mucho mayor a G.711. En otras palabras recupera

Page 38: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.4_Codificacion_de_la_voz.htm[24/11/2011 10:21:34 p.m.]

más información de la señal de audio y por lo tanto se dice que la calidad de la voz es superior. De hecho es elcodec utilizado en muchos de los teléfonos VoIP marcados como de alta definición o HD (High Definition). Algo muy interesante de G.722 es que pese a tener una taza de muestreo mayor a la de G.711 y de que laresolución de cada muestra es también mayor a la de dicho codec, el consumo de ancho de banda es casi el mismo,es decir 64kbit/s. Esto es posible debido a que G.722 utiliza un algoritmo diferente. Si analizamos rápidamente el ancho de banda de voz humana que este codec puede capturar (de acuerdo al teoremade Nyquist estudiado en el capítulo anterior), veremos que la taza de muestreo de 16kHz nos permite digitalizarfrecuencias de hasta 8kHz. Es decir una banda del doble de ancho que G.711, incluyendo frecuencias altas. Estasfrecuencias altas contienen matices agudos que hacen que la voz sea más entendible y clara. Con la reciente aparición en el mercado de teléfonos que dicen proveer audio de Alta Definición (HD) hemos vistoun incremento en el uso de este codec. El lector podría pensar entonces que se trata de una tecnología nueva. Sinembargo, G.722 es un estándar de 1988.

G.729 Este también se trata de una recomendación ITU cuyas implementaciones ha sido históricamente licenciadas. Estoquiere decir que usualmente hay que pagar por ellas. La ventaja en la utilización de G.729 radica principalmente en su alta compresión y por ende bajo consumo deancho de banda. Esto lo hace atractivo para comunicaciones por Internet. Pese a su alta compresión no deteriora lacalidad de voz significativamente y por esta razón ha sido ampliamente usado a través de los años por muchosfabricantes de productos de VoIP. G.729 utiliza 8kbit/s por cada canal. Si comparamos este valor con el de G.711 (64kbit/s) notaremos que consume8 veces menos ancho de banda, lo cual a simple vista es un ahorro de recursos significativo.

Nota: Existen variaciones de G.729 que utilizan 6.4kbit/s y 11.8kbit/s. Para habilitar canales G.729 en Elastix se debe adquirir una licencia por cada canal.

GSM Muchas personas correctamente asumen que el codec GSM tiene algo que ver con el estándar de comunicacionescelulares. El estándar que define la tecnología celular GSM (Global System for Mobile communications) incluyeeste codec. La ventaja de este codec también es su compresión. Sin embargo, la calidad de voz se deteriora en relación a otroscodecs. Ya nos habremos fijado en esto cuando hemos hablado por un celular GSM alguna vez. GSM comprime aproximadamente a 13kbit/s y viene habilitado por defecto en Elastix.

Anterior Ir a índice Siguiente

Page 39: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.5_Sobrecarga_de_protocolos.htm[24/11/2011 10:21:36 p.m.]

Anterior Ir a índice Siguiente

2.5 Sobrecarga de protocolos Por lo anteriormente visto, para transportar la voz de un lugar a otro en una red de paquetes necesitamos la ayudade algunos protocolos. Así también, ya nos habremos dado cuenta de que estos protocolos transmiten dataadicional que ocupa ancho de banda adicional a la voz propiamente dicha. Algunos de ellos son Ethernet, IP, UDPy RTP. En resumen, esto hace que el ancho de banda real para transmitir la voz sea mayor al del codec. Por ejemplo, para transmitir voz usando G.711 en teoría deberíamos usar 64Kbps (peso del codec) cuando enrealidad usamos 95.2Kbps de ancho de banda. En otros codecs de mayor compresión la sobrecarga es incluso mássignificativa (porcentualmente hablando). Hagamos un ejercicio sencillo usando como ejemplo el codec G.711. Veamos la siguiente figura para ilustrar mejorel ejercicio.

Ilustración de la sobrecarga de protocolos usando G.711

Calculemos el ancho de banda para G.711 basándonos en la figura anterior, la cual nos muestra el desperdicio uoverhead de cada protocolo. Sumemos ahora todos estos bytes enviados. Bytes transmitidos por cada 20ms de audio = 38 + 20 + 8 + 12 + 160 = 238 bytes Bits transmitidos por cada 20ms de audio = 238 bytes * 8 bits/byte = 1904 bits Bits transmitidos cada segundo = 1904 bits/20ms * 1000 ms/seg . = 95,200 bits/s = ¡95.2Kbps!

Comparativa de codecs A continuación mostramos una tabla que muestra el overhead para algunos de los codecs más populares soportadospor Asterisk.

Page 40: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_2/2.5_Sobrecarga_de_protocolos.htm[24/11/2011 10:21:36 p.m.]

Codec Ancho de banda

códecAncho de banda realEthernet

Porcentaje de overhead

G.711 64 Kbps 95.2 Kbps 48.75%iLBC 15.2 Kbps 46.4 Kbps 205.26%G.729A 8 Kbps 39.2 Kbps 390%

Anterior Ir a índice Siguiente

Page 41: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.1_Introduccion.htm[24/11/2011 10:21:36 p.m.]

Anterior Ir a índice Siguiente

3Linux para Administradores de Elastix

Sólo los débiles hacen copias de seguridad en cintas: los hombres de verdad tan solo suben suscosas importantes a un servidor ftp, y dejan que el resto del mundo las replique.

-- Linus Torvalds, creador de Linux

3.1 Introducción En este capítulo se repasarán algunos conceptos útiles de Linux para facilitan la tarea de los administradores deElastix. Si usted ya conoce cómo administrar su Elastix desde la línea de comandos de Linux puede saltarse estecapítulo e ir directamente al siguiente. Debido a que este no es un libro de Linux, no ahondaremos mucho en el tema ni hablaremos de la historia deLinux ni de sus ventajas. Si al leer este capítulo en algún momento le parece que estamos abordando los temas demanera muy general, esta ha sido la intención.Aunque este capitulo es un buen comienzo para el lector sin experiencia en Linux, le recomendamos capacitarse ensu administración ya que sin duda le facilitará las tareas como administrador de Elastix.

Anterior Ir a índice Siguiente

Page 42: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.2_Linea_de_comandos_Linux.htm[24/11/2011 10:21:38 p.m.]

Anterior Ir a índice Siguiente

3.2 Línea de comandos de Linux Una manera muy cómoda de administrar Elastix es desde la línea de comandos de Linux. La línea de comandos deLinux nos permite explotar al máximo el potencial de nuestro servidor de comunicaciones unificadas. Podemos ingresar a la línea de comandos directamente conectando un monitor y un teclado a nuestro equipoinstalado con Elastix. Alternativamente, se puede conectar remotamente a través del protocolo SSH. Si estamos en un equipo Windows debemos descargar un programa cliente para podernos conectar de maneraremota. El programa que recomendamos se llama PuTTY y basta hacer una búsqueda en Google por ese nombrepara encontrar el sitio de descargas. Sólo asegúrese de hacerlo desde el sitio oficial.

La aplicación PuTTY

Luego de ingresar los parámetros del servidor Elastix e iniciar la sesión podemos ejecutar comandos como siestuviéramos conectados directamente con un monitor y un teclado.

Page 43: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.2_Linea_de_comandos_Linux.htm[24/11/2011 10:21:38 p.m.]

Ejecutando PuTTY

Anterior Ir a índice Siguiente

Page 44: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.3_Comandos_basicos.htm[24/11/2011 10:21:39 p.m.]

Anterior Ir a índice Siguiente

3.3 Comandos básicos A continuación una lista de los comandos básicos más usados en Linux: Comando Descripciónls Enlista los archivos en el directorio actualls -la Enlista los archivos y sus atributoscd <directorio> Cambia de directoriocd .. Cambia al directorio padrecat <archivo> Muestra el contenido de un archivo en la

pantallapwd Muestra la ruta al directorio actualcp <archivo1> <archivo2> Copia un archivo o grupo de ellosmv <archivo1> <archivo2> Mueve un archivo. También se lo usa para

renombrar archivosrm <archivo> Elimina un archivotail -f <archivo> Muestra las últimas líneas de un archivo en

forma dinámicamkdir <directorio> Crea un directoriotar -xvzf <archivo>.tar.gz Descomprime un archivo tar.gztop Muestra un reporte en tiempo real de los

procesos que se ejecutan en el sistema.Puede ser ordenado por consumo dememoria o CPU. Muy útil para diagnóstico

find <directorio> -name<archivo>

Permite buscar archivos a partir de undirectorio determinado

vim <archivo> Programa para ver y editar archivos de textoplano

ifconfig Muestra información de las interfaces dered y permite modificarlas temporalmente

ps -aux Muestra un reporte de los procesos que seestán ejecutando en el servidor

reboot Reinicia el equiposhutdown -h now Apaga el equipo

Page 45: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.3_Comandos_basicos.htm[24/11/2011 10:21:39 p.m.]

Ejemplo de la ejecución del comando top

Anterior Ir a índice Siguiente

Page 46: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.4_Sistema_de_archivos.htm[24/11/2011 10:21:40 p.m.]

Anterior Ir a índice Siguiente

3.4 Sistema de archivos En Linux es muy importante la organización del sistema de archivos. Esta organización le otorga robustez e interoperabilidad a Linux pues los programas pueden predecir con mayorexactitud dónde se encuentran ciertos archivos para su correcto funcionamiento. Además, permite que los procesosescriban archivos de manera que otros componentes los entiendan. Esto minimiza los conflictos y en conjunto conel sistema de permisos añade más seguridad al sistema operativo.

Organización La organización de directorios que se mostrará a continuación no es arbitraria. Es producto de años de evolucióndesde las primeras versiones de UNIX hasta lo que hoy conocemos como Linux. Esta estructura de carpetas está ubicada en lo que se llama directorio raíz, o directorio principal. Este directorioraíz es el directorio de más alto nivel en el sistema de archivos y se representa con una diagonal “/”. Losdirectorios enlistados en la siguiente tabla residen todos en el directorio raíz. Directorio Descripciónsbin Incluye binarios que pueden ser ejecutados

solo por el administradorbin Contiene binarios necesarios para el

correcto funcionamiento del sistema. Losbinarios de esta carpeta pueden también serutilizados por los usuarios del sistema

boot Contiene el kernel y otros archivosnecesarios al momento de arranque

dev Incluye archivos que representandispositivos de hardware. Recordemos queen Linux prácticamente todo es un archivo

etc Contiene básicamente archivos deconfiguración para todo el sistema

home Aquí residen los directorios de los usuarios.Por ejemplo, el directorio /home/jorge/ es eldirectorio del usuario jorge

lib Contiene las librerías compartidas querequieren los programas. Algo análogo a losarchivos .dll en Windows

lost+found Cuando por alguna razón el sistema dearchivos se corrompe y hay que repararlo,los resultados de esa reparación se guardanen este directorio

mnt Este es un lugar común para montar otrossistemas de archivos o dispositivos. Porejemplo una unidad de CD-ROM o unamemoria USB

Page 47: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.4_Sistema_de_archivos.htm[24/11/2011 10:21:40 p.m.]

opt Contiene paquetes de software quenormalmente no son parte de la instalaciónoriginal

proc Este es un directorio virtual (ya querealmente reside en la memoria) donde elkernel y drivers escriben archivos para queotros programas los puedan leer. Porejemplo, aquí es donde los drivers deDAHDI escriben ciertos archivos en la ruta/proc/dahdi/

root Contiene archivos del usuario root ya queeste no tiene uno del tipo /home/root/

tmp Guarda archivos temporalesusr Es uno de los directorios más importantes y

contiene información para ser compartidacon los usuarios del sistema. Es decir, aquíresiden programas junto con ladocumentación necesaria y hasta libreríasrelacionadas. Usualmente, este directorio nocontiene información que cambieconstantemente

var Contiene información en constante cambiocomo logs o colas de emails. Por ejemplo,aquí reside el log de Asterisk en la ruta/var/log/asterisk/full

Permisos En Linux cada directorio o archivo tiene permisos de acceso y estos permisos pueden ser básicamente de 3 tipos:

LecturaEscrituraEjecución

Los permisos pueden ser aplicados al dueño del archivo, a un grupo de usuarios del sistema, o globalmente a todoslos usuarios del sistema. Para cada una de estas entidades se puede establecer permisos diferentes. Dicho todo lo anterior podemos establecer la siguiente matriz de permisos que sería válida para un determinadoarchivo del sistema: dueño grupo otros usuariosLectura x x xEscritura x Ejecución x x x

En el ejemplo anterior, el usuario dueño tiene todos los permisos sobre el archivo mientras que los usuarios delgrupo y otros usuarios globales del sistema solo tienen permisos de lectura y ejecución.

Page 48: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.4_Sistema_de_archivos.htm[24/11/2011 10:21:40 p.m.]

Existe sin embargo una notación más sencilla para expresar esta información. Esta notación compuesta de 10caracteres simplifica el despliegue de la información de permisos y permite mostrarlos en una sola línea. Esto esmuy útil cuando se quieren ver permisos de muchos archivos aunque toma tiempo acostumbrarse. Por ejemplo, lamatriz de permisos del ejemplo anterior se puede expresar de la siguiente manera (hemos incluido la posición decada permiso como un número del 0 al 9):

-rwxr-xr-x0123456789

Donde,

El caracter en posición 0 representa el tipo de archivo. Si se llena con la letra “d” significa que se trata de undirectorio.Los caracteres en posiciones 1, 2 y 3 representan los permisos de lectura, escritura y ejecución para el dueñodel archivo.Los caracteres en posiciones 4, 5 y 6 representan los permisos de lectura, escritura y ejecución para el grupoal que pertenece el archivo.Los caracteres en posiciones 7, 8 y 9 representan los permisos de lectura, escritura y ejecución para otrosusuarios.

Ahora veamos un ejemplo de un listado donde podremos apreciar diferentes permisos: $ ls -ladrwxrwxr-x 4 edgar edgar 4096 2008-09-01 21:20 Codigo-rw-rw-r-- 1 edgar edgar 53058 2008-08-04 01:31 comohemo.mid-rw-rw-r-- 1 edgar edgar 22785270 2008-08-07 12:09 dlj173.pdfdrwxrwxr-x 3 root root 4096 2008-08-26 17:21 elastixdrwxrwxr-x 2 test prueba 4096 2008-09-11 13:03 flashingfopdrwxrwxr-x 3 edgar edgar 4096 2008-08-04 22:18 fpbx-rw-rw-r-- 1 edgar edgar 398439 2008-08-19 19:19 gforge_manual.pdf-rwxrw-r-- 1 edgar edgar 102135 2008-09-07 18:53 index2.html-rw-rw-r-- 1 user4 101 3535 2008-08-19 23:20 install-cerosdrwxrwxr-x 3 edgar edgar 4096 2008-08-03 01:52 installers-rw-rw-r-- 1 edgar edgar 6860 2008-08-19 23:12 ksraid.cfgdrwxr-xr-x 4 edgar edgar 4096 2008-08-06 12:14 lw-rw-rw-r-- 1 edgar edgar 1020152 2008-07-30 14:00 Magic Button.pdfdrwxrwxr-x 3 edgar edgar 4096 2008-09-02 17:25 monitoring-rw-rw-r-- 1 edgar edgar 14341913 2008-08-12 01:59 prbx1.zip-rw-rw-r-- 1 edgar edgar 7195354 2008-08-03 01:51 rotron1.7.1.tar.bz2-rw-rw-r-- 1 edgar edgar 25343 2008-08-13 00:25 roundcube.diff-rw-rw-r-- 1 edgar edgar 12167 2008-08-01 23:03 src-php.tar.bz2drwxr-xr-x 18 edgar edgar 4096 2008-08-13 09:38 wanpipe-3.2.7-rw-rw-r-- 1 edgar edgar 16106184 2008-08-29 17:40 wanpipe-3.2.7.1.tgz-rw-rw-r-- 1 edgar edgar 20525 2008-09-08 17:14 xorcom_test.txt-rw-rw-r-- 1 edgar edgar 9277 2008-09-08 02:10 Xorcom_logo.png

Ejemplos de permisos de archivos

Representación numérica de permisos Aparentemente vamos a complicar las cosas un poco más aquí pero ya veremos más adelante la utilidad de poderrepresentar la matriz de permisos de una forma más condensada llamada representación numérica u octal depermisos. La idea es que los tres caracteres que definen los permisos para cada una de las tres entidades involucradas (dueño,grupo y otros) pueden ser representados por un solo número. De esta forma toda la información de permisos de un

Page 49: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.4_Sistema_de_archivos.htm[24/11/2011 10:21:40 p.m.]

archivo pueden ser representados por 3 de estos números. Por ejemplo, 755. Donde el primer dígito representa lospermisos del dueño, el segundo dígito los permisos del grupo y el tercer dígito los permisos de otros usuarios opermisos globales. Puede ser complicado entender al principio pero sin duda se trata de un formato más condensado. Veamos elsiguiente ejemplo: -rwxr-xr-x equivale a 755 Resulta que cada uno de los tres caracteres que representan un permiso para una entidad dada puede serreemplazado por 1 o 0 de tal manera que obtenemos un número binario. Este número binario se traduce a suequivalente decimal (realmente deberíamos decir octal aquí) como se ve a continuación.. -rwxr-xr-x Transformado a binario constaría de los siguientes tríos (sin tomar en cuenta la primera posición 0 correspondienteal directorio): 111 101 101 y ahora en su equivalente decimal

755 En fin, para los que no les gusta calcular binario quizás la siguiente tabla sea útil. Versión texto Versión binaria Versión octal--- 000 0--x 001 1-w- 010 2-wx 011 3r-- 100 4r-x 101 5rw- 110 6rwx 111 7

Ahora se estarán preguntando ¿para qué nos sirve esta notación numérica? Bueno, resulta que de esta manera es mucho más fácil manipular los permisos de los archivos mediante comandosy eso es precisamente lo que veremos a continuación.

Cambiando permisos y dueños de archivos Las tareas de cambio de permisos y dueños de archivos pueden ser realizadas fácilmente gracias a los comandoschmod y chown respectivamente.

Page 50: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.4_Sistema_de_archivos.htm[24/11/2011 10:21:40 p.m.]

chmod toma como parámetros los permisos en modo numérico y el nombre del archivo al que se desea realizar elcambio. Por ejemplo: $ ls -la archivo_prueba-rw-rw-r-- 1 edgar edgar 0 2008-09-19 04:21 archivo_prueba$ chmod 755 archivo_prueba$ ls -la archivo_prueba-rwxr-xr-x 1 edgar edgar 0 2008-09-19 04:22 archivo_prueba

El comando chmod también se puede usar recursivamente para cambiar los permisos de todos los archivos dentrode una carpeta. Esto se hace con la opción R. Por ejemplo: chmod –R 755 nombre_carpeta/ Para cambiar el dueño y grupo asociado con un archivo determinado podemos usar el comando chown. Porejemplo para cambiar los permisos del archivo anterior al usuario y grupo root ejecutamos lo siguiente (nótese laseparación del usuario y grupo por un punto “.”). # ls -la archivo_prueba-rwxr-xr-x 1 edgar edgar 0 2008-09-19 04:23 archivo_prueba# chown root.root archivo_prueba# ls -la archivo_prueba-rwxr-xr-x 1 root root 0 2008-09-19 04:24 archivo_prueba

Al igual que el comando chmod, el comando chown también soporta la opción recursiva con R.

Anterior Ir a índice Siguiente

Page 51: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.5_RPMs_y_actualizaciones_via_Yum.htm[24/11/2011 10:21:42 p.m.]

Anterior Ir a índice Siguiente

3.5 RPMs y actualizaciones vía Yum Los paquetes de software que se incluyen en Elastix vienen en un formato llamado RPM. Este es un formatoheredado de Red Hat y su nombre significa Red Hat Package Manager por sus siglas en inglés. Esto quiere decirque los instaladores de muchos paquetes de software adicional pueden ser instalados en Elastix de manera sencillautilizando paquetes comprimidos usualmente con la extensión .rpm. Los RPMs también nos permitirán actualizar paquetes de software y se encargarán de resolver las dependenciasnecesarias para que dichos paquetes no causen problemas en el sistema. Esto se logra gracias a que el sistema RPMmantiene una base de datos interna de todos los paquetes instalados con sus respectivas dependencias y versiones.Además nos provee con un comando muy útil para manipular las instalaciones, des-instalaciones, actualizaciones yotras tareas importantes. A continuación se muestran algunas opciones de uso del comando rpm: Acción a realizar ComandoInstalación de RPMs rpm -ivh <paquete>.rpm

Actualización de un RPM rpm -Uvh <paquete>.rpm

Eliminación de un RPM rpm -e <paquete>.rpm

Obtener información de un archivoRPM

rpm –qpi <paquete>.rpm

Obtener un listado de todos los RPMsinstalados en el sistema

rpm -qa

Yum al rescate La instalación manual de RPMs mediante el comando rpm está bien para muchas de las tareas. Sin embargo, hayocasiones en las cuales instalar RPMs de esta manera es tedioso y complicado. Un ejemplo de esto es cuandoinstalamos paquetes RPMs complejos que tienen muchas dependencias. Al momento de instalar dicho paqueteresulta que nos damos cuenta que tenemos que instalar otro paquete necesario y tenemos que buscarlo en Internetpara instalarlo. Muchas veces un RPM tiene decenas o hasta cientos de dependencias lo que por supuesto nos llevaría horassolucionar manualmente. Adicionalmente a este problema de dependencias existe otro y es el de la confiabilidad de los RPMs. Es decir,luego de horas y horas de instalar nuestros paquetes manualmente nos damos cuenta de que uno de ellossobrescribió un archivo importante del sistema y corrompió nuestro servidor Elastix. ¡Vaya dolor de cabeza! La solución es una utilidad llamada yum Este programa nos ayuda a instalar paquetes RPM desde repositorios y lohace de una manera muy amigable. La mayoría de las distribuciones más populares, y Elastix no es la excepción, mantienen repositorios de paquetesoficiales de software accesibles gratuitamente a través de Internet. Ellos hacen el mayor esfuerzo para que dichospaquetes no tengan problemas de dependencias entre sí. Además los paquetes de los repositorios oficiales son

Page 52: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_3/3.5_RPMs_y_actualizaciones_via_Yum.htm[24/11/2011 10:21:42 p.m.]

probados para evitar incompatibilidades en lo posible. Es por esta razón que si se usa Elastix lo recomendable esque se instalen paquetes desde el repositorio oficial. A continuación mostramos algunos comandos yum útiles: Comando Descripciónyum update Actualizar todo el sistemayum update <paquete> Actualiza solo el paquete especificado y

todas sus dependenciasyum install <paquete> Instala el paquete especificado y todas sus

dependencias

Nota: Cabe destacar que Elastix nos provee de una interfaz Web amigable para actualizar paquetes yadministrar repositorios. Por los tanto, los procedimientos de actualización manuales aquí descritos sedejarán para casos excepcionales. Se recomienda en lo posible utilizar la interfaz Web.

Anterior Ir a índice Siguiente

Page 53: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.1_Que_es_Asterisk.htm[24/11/2011 10:21:42 p.m.]

Anterior Ir a índice Siguiente

4Asterisk: Conceptos Esenciales

Si una idea no es absurda al principio, entonces no merece la pena.-- Albert Einstein

4.1 ¿Qué es Asterisk? Asterisk es un software de central telefónica (PBX) con capacidad para voz sobre IP que es distribuido bajolicencia libre. Partiendo de este concepto muy básico Asterisk no es una central telefónica cualquiera; se trata de una centraltelefónica rica en características que en otros tiempos solo eran accesibles mediante la compra de productoscostosos. Esto ha hecho que muchas empresas consideren a Asterisk como una seria opción al momento de planificar suproyecto telefónico y por esta razón Asterisk ha tenido gran acogida a nivel mundial. Al ver la oportunidad de negocio muchos fabricantes se han sumado a ofrecer hardware telefónico compatible conAsterisk, principalmente tarjetas electrónicas para conexión con la PSTN. Esto ha hecho que la oferta de centralestelefónicas basadas en Asterisk crezca rápidamente en los últimos tiempos. Asterisk es uno de los componentes más importantes de Elastix y quien provee la mayoría de las característicastelefónicas de la distro.

Anterior Ir a índice Siguiente

Page 54: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.2_Breve_historia_Asterisk.htm[24/11/2011 10:21:43 p.m.]

Anterior Ir a índice Siguiente

4.2 Breve historia de Asterisk Asterisk fue concebido y desarrollado por Mark Spencer. En un principio por una necesidad personal puesnecesitaba una central telefónica para la pequeña empresa de soporte que estaba fundando llamada “Linux SupportServices”. Inicialmente pensó en adquirir una central telefónica pero pronto se dio cuenta que estaba lejos de su presupuesto.Así que luego de pensarlo un poco decidió crear la suya propia y comenzó a codificar lo que hoy conocemos comoAsterisk. En 1999, cuando tuvo un código funcional, decidió liberarlo bajo licencia GPL. A pesar de lo que se pueda pensar, Mark no era un novato en el mundo del software libre. Él ya había participadoactivamente en el desarrollo del cliente de mensajería Gaim, actualmente llamado Pidgin, uno de los más popularesen el ámbito del software libre. En el 2002, Linux Support Services se convertiría en Digium, quien actualmente ofrece productos y serviciosrelacionados con Asterisk y se encarga del desarrollo del software como tal. Cabe resaltar que en un principio Mark se dio cuenta de que su software necesitaba interactuar con hardwaretelefónico. Fue entonces cuando se encontró con el proyecto Zaptel, un proyecto de código abierto creado por JimDixon. Zaptel tenía el objetivo de crear drivers abiertos para tarjetas telefónicas de computadora. A partir de allíAsterisk y Zaptel caminarían de la mano hasta el punto que en la actualidad los dos proyectos son mantenidos porDigium. En 2008 Digium decidió cambiar el nombre del proyecto que mantenían de Zaptel a DAHDI.

Anterior Ir a índice Siguiente

Page 55: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.3_Funcionalidad_provista_por_Asterisk.htm[24/11/2011 10:21:44 p.m.]

Anterior Ir a índice Siguiente

4.3 Funcionalidad provista por Asterisk Como ya hemos dicho Asterisk es un software de central telefónica rico en características. Al momento de escribireste libro las características soportadas más relevantes son las que enlistamos a continuación.

Contestación automática de llamadasTransferencia de llamadasOpción de no molestarParqueo de llamadasContestación de llamada desde extensión remotaMonitoreo y grabación de llamadasVoicemailConferenciasReportación de llamadasColas de atenciónLlamada en esperaIdentificador del llamanteBloqueo por llamante identificadoEnvío y recepción de faxListado interactivo del directorio de extensionesInteractive voice response (IVR)Música en esperaManejo de comportamiento por horariosFollow me

Contestación automática de llamadas Asterisk provee la facilidad de configurar una contestadora automática que ayuda al manejo del flujo de llamadasentrantes contestándolas automáticamente sin necesidad de una operadora en vivo. Esta funcionalidad ha sidodiseñada para empresas que reciben altos flujos de llamadas y que no poseen el personal necesario para manejar eltráfico de llamadas entrantes. La contestadora responde a los dígitos marcados por el teclado de la persona que llama, encamina las llamadas aextensiones específicas, provee acceso a información pregrabada y toma mensajes 24 horas al día.

Transferencia de llamadas En Asterisk existen dos métodos para transferir llamadas: transferencia atendida y transferencia ciega. En latransferencia atendida se llama primero al destinatario para avisarle que se le trasferirá una llamada. En latransferencia ciega se transfiere simplemente la llamada sin conversar con el destinatario previamente.

Opción de no molestar

Page 56: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.3_Funcionalidad_provista_por_Asterisk.htm[24/11/2011 10:21:44 p.m.]

Esta opción permite a cualquier usuario configurar su extensión para que no reciba llamadas por un período detiempo. Cualquier llamada entrante a esta extensión será ruteada automáticamente al buzón de correos de la misma.

Parqueo de llamadas El parqueo de llamadas permite al usuario que recibe una llamada enviarla a un espacio de parqueo, para volver aatenderla desde otra extensión. Este tipo de acción es útil en muchas situaciones como cuando un técnico recibeuna llamada a su escritorio la cual requiere que él se ubique de frente a un servidor localizado tres pisos másarriba.. En este caso, la opción es enviar la llamada a un cuarto temporal o espacio de parqueo, donde mientrastanto el llamante escuchará la música en espera configurada. El técnico puede retomar la llamada una vez quellegue al servidor.

Contestación de llamada desde extensión remota Esta característica permite atrapar una llamada que se encuentra timbrando en una extensión que no es la suya.También se la conoce como call pickup, debido a su nombre en inglés.

Monitoreo y grabación de llamadas Asterisk permite monitorear y grabar llamadas. El monitoreo se suele usar para fines de control de calidad de losoperadores telefónicos o de los agentes de ventas. Para esto existe la facilidad de que a través de la digitación de uncódigo predeterminado se permita escuchar en línea la conversación sostenida por una extensión cualquiera. Adicionalmente existe la facilidad de grabar las conversaciones de cualquier extensión en forma aleatoria óprogramada previamente. Estas grabaciones se almacenarán en el disco duro del servidor Asterisk para su posteriorrevisión.

Voicemail (Buzón de mensajes de voz) El buzón de mensajes de voz es una aplicación que permite guardar y escuchar mensajes dejados por llamantes queno pudieron ser atendidos. Para acceder al buzón de mensajes de voz hay que digitar un código predeterminado. Asterisk nos preguntará pornuestra clave y a continuación accederemos a los mensajes disponibles.

Conferencias Una conferencia no es más que una llamada telefónica donde pueden conversar varios participantes a la vez. Paraacceder a esta funcionalidad se crean cuartos de conferencia. Cada cuarto se encuentra asociado a un número comosi se tratase de una extensión. Entonces, para acceder a una conferencia basta con marcar el númerocorrespondiente al cuarto de conferencia deseado. Es posible configurar algunas características interesantes a un cuarto de conferencias determinado, como porejemplo: limitar el número de participantes, solicitar una contraseña al ingreso o moderar el cuarto de conferencias.

Reportación de llamadas

Page 57: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.3_Funcionalidad_provista_por_Asterisk.htm[24/11/2011 10:21:44 p.m.]

Asterisk genera Call Detail Records (CDRs) o Registros de Detalle de Llamadas y los puede almacenar en unabase de datos. Accediendo a esta base de datos, se pueden generar reportes que detallan qué extensión llamó a quénúmero, si la llamada fue contestada o no, cuánto duró la llamada, o por qué puerto o línea telefónica se realizó lallamada.

Colas de atención Esta característica permite que un gran número de llamantes puedan permanecer en espera hasta que unrepresentante o recurso esté disponible para dar asistencia. Esto asegura que los llamantes no terminaránobligatoriamente en el voicemail, lo cual puede resultar molestoso. Es decir, con las colas de atención nosaseguramos que el llamante siempre tenga la oportunidad de ser atendido por una persona. El tiempo que elllamante permanece en espera puede aprovecharse para darle a conocer más servicios o productos de la compañía,ofertas especiales, anuncios informativos ó simplemente se puede proporcionar música en espera.

Llamada en espera Esta característica permite que la persona que se encuentra atendiendo una llamada y recibe otra, pueda interrumpirtemporalmente su primera conversación para atender la segunda. Para alertar a la persona que una segunda llamadaestá ingresando se le reproduce un sonido característico. En algunos escenarios este sonido no es deseable, porejemplo en las conexiones telefónicas para transferencia de datos (Ej.: fax). En estos casos se opta por deshabilitaresta característica ya que provoca errores en la transmisión del fax.

Identificador del llamante Esta señal es enviada entre las señales de ring o durante el proceso de establecimiento de la llamada, antes de quesea contestada. Asterisk aprovecha esta facilidad y a nivel de extensiones IP soporta plenamente su manejo. Sinembargo a nivel de líneas de la red telefónica pública conmutada es el proveedor de estas quien debe habilitar oproporcionar esta característica. Se la conoce también como Caller ID.

Bloqueo por llamante identificado Esta característica previene que alguien con identificador de llamante vea el número desde el que usted llama. Estafacilidad de ocultar el ID puede ser completa o selectiva. No todas las redes de telefonía pública soportan estacaracterística. En Asterisk esta característica también incluye bloquear una llamada entrante en función del ID.

Envío y recepción de fax Asterisk permite detectar automáticamente cuando un llamante está intentando enviar un fax. Se puede poner comoparte del mensaje de bienvenida de la central telefónica una frase que diga: “Si quiere enviar un fax, envíeloahora”. Esto nos ayuda a eliminar papel, prescindir de máquinas ó puertos telefónicos exclusivos para fax ydigitalizar la información recibida como fax. Luego de ser digitalizado, este documento puede ser enviado vía e-mail a una cuenta específica para su revisión.

Listado interactivo del directorio de extensiones

Page 58: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.3_Funcionalidad_provista_por_Asterisk.htm[24/11/2011 10:21:44 p.m.]

Asterisk cuenta con todo el directorio telefónico del personal de la empresa (nombre, apellido y extensión) en subase de datos. Esta facilidad permite que la persona que llama pueda digitar desde su teléfono los númeroscorrespondientes a las 4 primeras letras del apellido ó nombre de la persona con la que desea hablar. Esto puedeproporcionar una alternativa para llamantes que no conocen la extensión de la persona a quien que quierencontactar pero conocen solo su apellido ó nombre.

Interactive voice response (IVR) A través de esta característica se proporciona acceso a opciones telefónicas que mejoran la forma en la cual unsistema telefónico acepta y distribuye sus llamadas. Con un menú de IVR es posible distribuir las llamadas entrantesde una manera precisa. Esto ayudará a incrementar el desempeño de los empleados y la satisfacción de los clientes,ya que se agilita el acceso a los servicios y a la información que posee su compañía. Con esta facilidad seproporcionan procesos de auto atención que permitirán incluso prescindir de una recepcionista en ciertos casos.Mediante el uso de esta característica se pueden crear menús de activación por dígitos ó por comandos de voz paraejecutar inclusive consultas a otros sistemas de cómputo como bases de datos.

Música en espera Asterisk permite utilizar cualquier archivo en formato mp3 o wav como música de fondo. Ésta será reproducidacuando algún llamante externo o interno se encuentra esperando a que un representante de la compañía lo atienda.Estos archivos pueden ser inclusive agrupados por categorías para reproducir diferentes melodías a diferentesgrupos de llamantes.

Manejo de comportamiento por horarios Es posible configurar Asterisk para que tenga un tratamiento diferente para con las llamadas (tanto entrantes comosalientes) dependiendo de la hora del día, día del mes o mes del año. El ejemplo más básico es cuando se quiereque las llamadas entrantes recibidas fuera de horarios de oficina reciban un mensaje pregrabado sugiriendo alllamar nuevamente al siguiente día.

Follow me Esta característica, conocida en español como sígueme, permite predefinir una secuencia de llamadas simultáneas oen secuencia para poder ubicar a un usuario. Por ejemplo, se podría definir que cuando la extensión del gerente dela compañía timbre y este no conteste la llamada se redirija a su celular y otros teléfonos de contacto. Se puedenespecificar tiempos de gracia antes de que el siguiente número de teléfono sea marcado.

Anterior Ir a índice Siguiente

Page 59: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.4_Funcionamiento_Asterisk.htm[24/11/2011 10:21:45 p.m.]

Anterior Ir a índice Siguiente

4.4 Funcionamiento de Asterisk

Directorios de Asterisk Asterisk organiza sus archivos distribuyéndolos entre algunos directorios. Los más importantes son los siguientes. Directorio Descripción/etc/asterisk/ Lugar donde residen los archivos de

configuración de Asterisk/usr/lib/asterisk/modules/ Contiene los módulos de Asterisk/usr/sbin/ Incluye el binario de Asterisk/var/lib/asterisk/agi-bin/ Lugar donde residen los scripts AGI/var/lib/asterisk/mohmp3 Contiene archivos para música en espera/var/lib/asterisk/sounds Incluye sonidos que Asterisk utiliza como

prompts de voz/var/spool/asterisk/ Lugar donde Asterisk guarda archivos que

genera producto de su funcionamiento comovoicemails y grabaciones de llamadas

/var/run/ Guarda archivos con información deprocesos (PIDs)

/var/log/asterisk/ Aquí residen los archivos de log de Asteriskcomo los CDRs o el /var/log/asterisk/full

Estructura modular Asterisk utiliza la idea de módulos para extender su funcionalidad. Es tan importante la funcionalidad residente enlos módulos que sin ellos Asterisk por si solo no cumpliría ninguna función interesante. Estos módulos residen en la carpeta /usr/lib/asterisk/modules/ y son archivos con la extensión .so Los módulos pueden ser controlados a través del archivo de configuración /etc/asterisk/modules.conf.Este archivo instruye a Asterisk a que cargue o no un módulo específico a través de las directivas load ynoload. Por omisión en Elastix todos los módulos tratan de ser cargados. A continuación un fragmento del archivo modules.conf que viene por defecto con Elastix. Aquí se puedeobservar cómo se le instruye a Asterisk a que no cargue algunos módulos en el arranque. ;; DON'T load the chan_modem.so, as they are obsolete in * 1.2 noload => chan_modem.sonoload => chan_modem_aopen.so

Page 60: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.4_Funcionamiento_Asterisk.htm[24/11/2011 10:21:45 p.m.]

noload => chan_modem_bestdata.sonoload => chan_modem_i4l.so ; Ensure that format_* modules are loaded before res_musiconhold;load => format_ogg_vorbis.soload => format_wav.soload => format_pcm.soload => format_au.so

Adicionalmente se pueden cargar módulos en tiempo real a través de la consola de Asterisk (no confundir con lalínea de comandos de Linux) con el comando: module load <modulo> Más adelante veremos más de la consola de Asterisk o CLI.

Anterior Ir a índice Siguiente

Page 61: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.5_Proyecto_DAHDI.htm[24/11/2011 10:21:46 p.m.]

Anterior Ir a índice Siguiente

4.5 El proyecto DAHDI A pesar de ser un gran producto de software, Asterisk no puede hacer todo el trabajo por sí solo. Uno de lospaquetes de software que lo complementa se llama DAHDI. Básicamente DAHDI es un conjunto de drivers para controlar hardware telefónico como tarjetas PCI o PCI Expressque nos permiten conectarnos a la PSTN. Estos drivers se comunican con Asterisk a través de un módulo de Asterisk llamado chan_dahdi.so que seconfigura a través del archivo de configuración /etc/asterisk/chan_dahdi.conf. Adicionalmente DAHDI tiene sus propios archivos de configuración, independientes de Asterisk, que seencuentran en la carpeta /etc/dahdi/.

Nota: En versiones de Elastix menores a 1.5 se utiliza el software del proyecto Zaptel en lugar de DAHDI.Esto quiere decir que los archivos de configuración para los drivers de telefonía tienen nombres diferentes.En estos casos se recomienda, como referencia, consultar la primera edición de la presente obra.

Diagrama simplificado de la interacción de Asterisk con DAHDI

Breve historia de DAHDI A pesar del cambio de nombre de Zaptel a DAHDI y toda la confusión que esto generó en un principio, no hay queolvidar que el origen de DAHDI estuvo en el proyecto Zaptel. Primero porque hay que dar el crédito merecido aquienes trabajaron en el proyecto original y segundo para no olvidarnos de la historia. A continuación un breveresumen de dicha historia.

Page 62: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.5_Proyecto_DAHDI.htm[24/11/2011 10:21:46 p.m.]

En el año 2000, Jim Dixon lanzó el proyecto Zaptel cuyo nombre era una abreviación de Zapata TelephonyProject. Lo nombró así en honor a Emiliano Zapata, héroe de la revolución mexicana. Los drivers fueron lanzadosbajo licencia GPL de tal manera que cualquiera pudo tener acceso al código. Inicialmente Zaptel contenía drivers para tarjetas Tormenta fabricadas por Zapata Telephony. No paso muchotiempo hasta que Digium comenzó a mejorar los drivers y extender el soporte para nuevos modelos de hardware,entre ellos los fabricados por Digium mismo. Es así que Digium se convirtió en el principal desarrollador de Zaptel. Luego de algunos años de mantener Zaptel, Digium cayó en cuenta de que Zaptel era una marca registrada por unacompañía vendedora de tarjetas de llamadas y para evitar cualquier posible confusión futura decidió cambiar denombre a sus drivers. El nombre elegido es DAHDI, que es un acrónimo de Digium Asterisk Hardware DeviceInterface o Interfaz de Dispositivos de Hardware de Asterisk de Digium en español. Digium finalizó el soporte oficial de Zaptel a partir de la versión Asterisk 1.6

Anterior Ir a índice Siguiente

Page 63: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.6_Configuracion_Asterisk.htm[24/11/2011 10:21:47 p.m.]

Anterior Ir a índice Siguiente

4.6 Configuración de Asterisk

Archivos de configuración Asterisk se puede configurar a través de algunos archivos de configuración ubicados en la ruta /etc/asterisk.Existen decenas de archivos de configuración en este directorio y se encuentran en texto plano para facilitar sumodificación. Debido a esto, podemos usar el editor vim u otro editor de línea de comandos de nuestra preferenciapara editarlos. Si bien todos estos archivos son importantes no todos son necesarios. Algunos de ellos ya han sido pre-configurados por Elastix para que no tengamos que modificarlos. Los más importantes se explican en la siguientetabla. Archivo Descripciónextensions.conf Define el plan de marcado. En Elastix se

incluyen otros archivos más para organizarel plan de marcado de mejor manera. Estosarchivos adicionales empiezan con lacadena extensions_

sip.conf Configura los dispositivos SIPiax.conf Configura los dispositivos IAXchan_dahdi.conf Define la configuración de los canales tipo

DAHDI.

Comentarios en los archivos de configuración Los archivos de configuración de Asterisk pueden contener comentarios. Un comentario empieza con el caracter depunto y coma. Una vez escrito este caracter el resto de la línea se convierte en un comentario. Es decir, esta línea esignorada por Asterisk al interpretar el archivo. Veamos un ejemplo de comentario. ;; El siguiente es un bloque de comentarios.; Como pueden ver puedo escribir cualquier cosa; aquí porque será ignorada por Asterisk.; Los comentarios son muy útiles para escribir; notas e información relativa a la configuración; que estamos escribiendo. ; Ahora si continúo con las directivas...; #include sip_general_custom.conf#include sip_nat.conf#include sip_registrations_custom.conf#include sip_registrations.conf

Page 64: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.6_Configuracion_Asterisk.htm[24/11/2011 10:21:47 p.m.]

Anterior Ir a índice Siguiente

Page 65: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

Anterior Ir a índice Siguiente

4.7 Plan de marcado (dial plan) El plan de marcado en Elastix reside principalmente en el archivo extensions.conf. Desde este se incluyenotros importantes archivos que contienen también porciones del plan de marcado. Los principales son:

extensions_additional.conf: Aquí reside el plan de marcado variable escrito por FreePBX, elcual es un componente importante de Elastix. Si se realizan cambios manualmente en este archivo, losmismos se perderán cuando FreePBX lo sobreescriba.

extensions_custom.conf: Aquí el usuario puede definir manualmente el plan de marcado. Estearchivo no es tocado por FreePBX por lo que es seguro editarlo sin temor a perder los cambios.

Todos estos archivos de plan de marcado están escritos en texto plano en un formato definido por Asterisk. Elcontenido de estos archivos se encuentra dividido en secciones llamadas contextos.

Contextos Los contextos sirven para agrupar la lógica del plan de marcado. Los contextos también a su vez incluir otroscontextos mediante la cláusula "include" o redirigir el hilo de ejecución del plan de marcado a otros contextosdependiendo de condiciones. Por ejemplo, luego de examinar el prefijo del número telefónico marcado, un contextopuede contener la lógica necesaria para rutear una llamada hacia la troncal correspondiente. Un contexto tambiénpuede agrupar la lógica necesaria para la aplicación de reloj despertador. También puede incluir lógica para accederal voicemail o para autenticar un número de PIN. En general, prácticamente todo en el plan de marcado seencuentra agrupado en contextos. Los contextos son los agrupadores u organizadores del plan de marcado. Cada contexto debe llevar un nombre único y este nombre va encerrado entre los símbolos “[“ y “]”. Acontinuación se encuentra un ejemplo donde se pueden observar dos contextos llamados app-pickup y ext-test [app-pickup]include => app-pickup-customexten => _**.,1,Noop(Attempt to Pickup ${EXTEN:2})exten => _**.,n,Pickup(${EXTEN:2}) [ext-test]include => ext-test-customexten => 7777,1,Goto(from-pstn,s,1)exten => 666,1,Goto(ext-fax,in_fax,1)exten => h,1,Macro(hangupcall,)

Fragmento del archivo extensions_additional.conf para ilustrar los contextos

Contextos reservados

Page 66: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

Hay dos nombres de contextos que están reservados para un propósito especial y son [general] y [globals] .

Extensiones Los contextos contienen instrucciones, conocidas como extensiones. Estas extensiones son líneas de plan demarcado que tienen la siguiente sintaxis. exten => nombre_extension, prioridad, aplicación

Nota: Normalmente asociamos el término extensión a un número de teléfono, pero en Asterisk el términoextensión va más allá de lo que normalmente conocemos. Una extensión es una serie de lógica de plan demarcado. Es más, cuando marcamos un número desde nuestro teléfono no necesariamente tiene que ringarotro teléfono pues podemos crear la lógica que queramos para este número dado. Por ejemplo podemoshacer que la llamada simplemente se cuelgue, que reproduzca un mensaje dado o funciones mucho máscomplejas.

Una extensión típica luce como la siguiente. exten => 4567,1,Answer()

Nombre de Extensión El nombre de extensión es un identificador numérico de la extensión. Llamémosle el número de teléfono por ahorapara simplificar el asunto. Existe una extensión especial no numérica llamada extensión s, a la que le prestaremos particular atención. La extensión s significa cualquier extensión. La letra s viene de la palabra start que significa inicio. Un ejemplodel uso de la extensión s es el siguiente. [prueba]exten => s,1,Answer()exten => s,2,noOp(“Prueba”)

La extensión s se usa cuando el usuario que realizo la llamada aun no ha presionado el numero de la extensión. Porejemplo, este es el caso de una llamada entrante que todavía se encuentra escuchando el IVR de bienvenida.

Prioridad La prioridad indica el orden en el que debe ser ejecutada una extensión dentro de un contexto. Es necesario que laprimera prioridad sea la 1 pues cuando Asterisk lee un contexto lo primero que busca es esta prioridad. Existe también una prioridad especial que es la prioridad n. La prioridad n significa que a la prioridad de lainstrucción anterior se le debe sumar uno. Esto es muy útil para facilitar la escritura del plan de marcado.

Page 67: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

Por ejemplo, revisemos el siguiente plan de marcado. exten => s,1,NoOp(“Hola este es solo un ejemplo”)exten => s,2,NoOp(“para demostrar”)exten => s,3,NoOp(“como usar la prioridad n”)

Este plan de marcado podría ser escrito de la siguiente manera usando la prioridad n. exten => s,1,NoOp(“Hola este es solo un ejemplo”)exten => s,n,NoOp(“para demostrar”)exten => s,n,NoOp(“como usar la prioridad n”)

Las prioridades también pueden contener etiquetas para facilitar su identificación ya que si usamos siempre laprioridad “n” será difícil acceder a una ubicación determinada dentro de un contexto. Esto se consigue con lasintaxis n(nombre_etiqueta).

Aplicación En las aplicaciones radica el verdadero poder del plan de marcado en Asterisk. Para hacer una analogía, lasaplicaciones son el equivalente a las funciones de un lenguaje de programación. Las aplicaciones nos permitiráncontestar una llamada o colgarla, reproducir música en espera, saltar a otros contextos entre otras muchasfunciones. Las aplicaciones también pueden recibir parámetros. Por ejemplo a la aplicación Dial( ) habrá que indicarle quénúmero marcar para que pueda realizar su labor. Más adelante en el presente capítulo se explicarán con más detalle las aplicaciones más comunes en el plan demarcado.

Variables Las variables en el plan de marcado son un concepto similar a las variables en un lenguaje de programación. Esdecir, son abstracciones que pueden almacenar información de naturaleza variable. Una variable tiene la siguientesintaxis. ${NOMBRE} Donde NOMBRE es el nombre de la variable. Las variables pueden ser de tres tipos: globales, de canal y pre-definidas.

Globales Son las variables definidas en la sección [globals] del archivo /etc/asterisk/extensions.conf, odirectamente dentro de /etc/asterisk/globals_custom.conf en cualquier Elastix. La palabra globalquiere decir que pueden ser referenciadas desde cualquier lugar.

Page 68: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

De canal Son las variables que se pueden definir usando el comando (o aplicación) Set().

Pre-definidas Asterisk se encarga de administrar algunos nombres de variables por su cuenta. Estos nombres se encuentran pre-definidos y contienen cierta información dependiendo del comportamiento de la llamada o de otros factores.Algunas variables pre-definidas son: ${CALLERID(all)}${CALLERID(name)}${CALLERID(num)}${CHANNEL}${CONTEXT}${EPOCH}${EXTEN}${SIPUSERAGENT}${UNIQUEID}

Nota: Hay un tipo adicional de variable introducida a partir de Asterisk 1.6 llamada variable compartida oshared. Esta variable permite que dos o más canales accedan a lo que de otra manera sería una variable decanal.

A continuación reproducimos un segmento del archivo extensions.conf que se distribuye por defecto conElastix. Aquí podemos ver algunas variables predefinidas como ${UNIQUEID}, ${BLINDTRANSFER} y${EPOCH}, y variables de canal como ${CALLFILENAME}. [macro-record-enable]exten => s,1,GotoIf($[${LEN(${BLINDTRANSFER})} > 0]?2:4)exten => s,2,ResetCDR(w)exten => s,3,StopMonitor()exten => s,4,AGI(recordingcheck,${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)},${UNIQUEID})exten => s,5,Noop(No recording needed)exten => s,999,MixMonitor(${CALLFILENAME}.wav)

Aplicaciones más comunes

Answer Sintaxis: Answer([delay]) Contesta un canal inmediatamente si éste está timbrando. Puede recibir opcionalmente el parámetro delay que indica a Asterisk que debe esperar un número determinado de milisegundos después de contestar la llamada parapasar a la siguiente aplicación.

Page 69: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

Background Sintaxis:Background(filename1[&filename2...][|opciones[|langoverride][|context]]) Reproduce un listado de archivos de audio en el fondo, es decir que devuelve el control a Asterisk, quien puedecontinuar ejecutando el plan de marcado mientras el audio es reproducido. Cuando termina de reproducir el últimoarchivo, su ejecución finaliza por lo que si se quiere seguir esperando por una extensión se debe usar la aplicaciónWaitExten() en conjunto.. Esta aplicación es típicamente usada para reproducir el mensaje de bienvenida de un IVR. La aplicación Background puede recibir algunas opciones: Opción Descripcións Saltarse la reproducción del audio si el canal no se encuentra contestadon No contestar el canal antes de reproducir los archivosm Dejar de reproducir el audio si un dígito marcado coincide con una

extensión existente en el contexto destino

Playback Sintaxis: Playback(filename1[&filename2...][,options]) Reproduce uno o más archivos de audio. La diferencia con la aplicación Background es que Playback reproducetodo el archivo de audio hasta el final y no retorna el control hasta que termina la reproducción.

Nota: No es necesario especificar la extensión del archivo de audio en esta función. Los archivos de audioson buscados en el directorio /var/lib/asterisk/sounds

Hangup Sintaxis: Hangup() Cuelga el canal y retorna el valor -1.

Goto Sintaxis: Goto([[context|]extension|]priority) Salta la ejecución del plan de marcado a un contexto, extensión y prioridades definidos. Si solo se pasa unparámetro se sobreentiende que se trata de una prioridad dentro del mismo contexto.

Dial

Page 70: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.7_Plan_de_marcado.htm[24/11/2011 10:21:48 p.m.]

Sintaxis: Dial(type/identifier, timeout, options, URL) Este comando es el responsable de marcar un canal especificado y lo vincula con el canal corriente.

Anterior Ir a índice Siguiente

Page 71: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.8_Asterisk_CLI.htm[24/11/2011 10:21:49 p.m.]

Anterior Ir a índice Siguiente

4.8 Asterisk CLI Asterisk CLI es el nombre que recibe la consola de Asterisk. Es decir, una línea de comandos para controlarAsterisk directamente. Para ingresar al CLI debemos ejecutar el siguiente comando desde la consola de Linux. # asterisk -rAsterisk 1.4.21.2, Copyright (C) 1999 - 2008 Digium, Inc. and others.Created by Mark Spencer <[email protected]>Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.This is free software, with components licensed under the GNU General PublicLicense version 2 and other licenses; you are welcome to redistribute it undercertain conditions. Type 'core show license' for details.=========================================================================Connected to Asterisk 1.4.21.2 currently running on elastix (pid = 2245)Verbosity is at least 3elastix*CLI>

Como podemos observar, obtenemos un prompt CLI> desde donde podemos ejecutar una serie de comandosque veremos en breve. El CLI también nos puede proveer información en tiempo real de la actividad de Asterisk. Además, podemoscontrolar el grado de detalle con el que queremos ver dicha información con algunos comandos. Los más usadosson los siguientes. elastix*CLI> core set debug 9Core debug was 3 and is now 9elastix*CLI> core set verbose 9Verbosity is at least 9

Mientras más altos los niveles de las variables debug y verbose, más detallada será la información mostrada.Por omisión el nivel de debug es 0 y el de verbose 3 en Elastix.

Nota: Debido a la gran cantidad de información que se puede generar con estos comandos es importantereestablecer los valores de las variables debug y verbose a los mínimos al finalizar nuestras tareas dediagnóstico. Caso contrario Asterisk continuará generando esta información detallada cuando realmente nola necesitamos, lo cual es un trabajo extra que consume recursos del sistema. En sistemas con muchaactividad este consumo adicional puede ser significativo y afectar el desempeño de las llamadas.

Comandos CLI A continuación proveemos una breve lista de los comandos de CLI más comunes. Comando Descripciónagi set debug on Permite habilitar el debug de scripts AGI.

Se apaga con “agi set debug off”

Page 72: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.8_Asterisk_CLI.htm[24/11/2011 10:21:49 p.m.]

core set debug channel Habilita el debug en un canal determinadocore set debug Permite cambiar el nivel de debugging. Se

apaga con “core set debug off”core set verbose Incrementa la intensidad del logging. Muy

útil en diagnósticocore show channels Muestra información actualizada de los

canales activosdialplan reload Recarga todo el plan de marcadodialplan show Muestra el plan de marcadohelp Muestra un listado con todos los comandos

de CLI disponiblesiax2 set debug Habilita el debug a nivel de IAX. Se

deshabilita con el comando “iax2 setdebug off”

iax2 show peers Muestra los peers definidos y algunainformación adicional como la dirección IPdesde donde se conectan, el estatus, entreotros datos

iax2 show registry Muestra información de registro IAX einformación como el estatus y la direcciónIP a la que se trata de conectar

module reload Recarga todos los módulos de Asterisk. Útilpara aplicar los cambios hechos en losarchivos de configuración

pri set debug on Habilita debug de los spans de la interfazPRI. Se apaga con “pri set debugoff”

core restart gracefully Reinicia Asterisk de manera ordenada. Esdecir, no permite iniciar nuevas llamadas yespera a que las existentes terminen paraproceder a reiniciar

core restart now Reinicia Asterisk de manera brusca (deinmediato)

core restart when convenient Reinicia Asterisk cuando no haya actividaden la central. Adecuado en ambientes deproducción donde no tenemos otra opciónque reiniciar la central pero no queremosque se corten llamadas en curso

sip set debug ip Habilita debug de SIP a nivel de unadirección IP específica

sip set debug peer Habilita debug de SIP a nivel de un peerespecífico

sip show peers Muestra un listado con todos los peers SIPconfigurados e información de cada uno deellos como su estatus

sip show registry Muestra un listado con los registros SIP einformación relevante de cada uno de ellos

core stop gracefully Detiene Asterisk de manera ordenada. Esdecir, no permite establecer nuevas llamadasy espera a que las existentes terminen paraproceder a detener el Asterisk.

Page 73: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_4/4.8_Asterisk_CLI.htm[24/11/2011 10:21:49 p.m.]

core stop now Detiene Asterisk de manera brusca (deinmediato)

core stop when convenient Detiene Asterisk cuando no haya actividaden la central. Adecuado en ambientes deproducción donde no tenemos otra opciónque apagar la central pero no queremos quese corten llamadas en curso

dahdi show status Muestra un listado de los canales DAHDI yun reporte de alarmas y errores

dahdi show channels Muestra un listado de los canales DAHDI yalgunos parámetros de funcionamiento.

elastix*CLI> dahdi show channels Chan Extension Context Language MOH Interpret pseudo default default 1 from-pstn default 2 from-pstn default 3 from-pstn default 4 from-pstn default 5 from-pstn default 6 from-pstn default 7 from-pstn default 8 from-pstn defaultelastix*CLI>

Listado de canales DAHDI producto del comando dahdi show channels

Anterior Ir a índice Siguiente

Page 74: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Anterior Ir a índice Siguiente

5Instalando Elastix

Hay hombres que luchan un día y son buenos. Hay otros que luchan un año y son mejores. Hay quienes luchanmuchos años, y son muy buenos. Pero hay los que luchan toda la vida, esos son los imprescindibles

-- Bertolt Bretch

5.1 Instalando desde CD Antes de comenzar, asegúrese de tener una copia de la última versión estable de Elastix, (la presente obra estábasada en la versión 2.0). Ésta puede ser descargada desde la página de descargas del proyecto Elastix enwww.elastix.org. Escoja la versión apropiada dependiendo si dispone de una máquina con procesador de 32 o 64bits.

Arranque desde CD Elastix se distribuye como un archivo de imagen tipo ISO, que puede ser quemado a un CD desde cualquiersoftware de grabación de CDs. Una vez quemada esta imagen en el CD, insértelo en su computador al momento de encenderlo. Asegúrese de quesu computador arranque de la unidad de CD-ROM, caso contrario deberá habilitar esta opción en el BIOS de sumáquina. Si todo va bien debería obtener una pantalla como la siguiente.

Page 75: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Pantalla de instalación inicial

Nota: El CD de instalación de Elastix formateará TODO el disco duro durante el proceso de instalaciónasí que asegúrese de no tener información que vaya a necesitar en su disco duro.

El proceso de instalación iniciará automáticamente dentro de diez segundos. Usted podría presionar la tecla deEnter si no desea esperar este tiempo.

Preferencias y bienvenida Luego de cargar algunos programas necesarios para iniciar la instalación, el proceso nos solicitará el idioma queserá utilizado para formular preguntas y mostrar mensajes a lo largo del proceso de instalación. Escoja el idiomaespañol (Spanish) utilizando las teclas de flechas de su teclado. Usando la tecla de TAB posicione el cursor sobreOK y presione la tecla de Enter.

Selección de idioma para instalación

A continuación, proceda a escoger el tipo de teclado de acuerdo al idioma. Si su teclado es de idioma españolseleccione la opción es.

Page 76: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Selección de tipo de teclado

Particiones del disco duro El siguiente es el paso crítico de la instalación ya que configura las particiones del disco duro. Si usted es unadministrador experimentado, podría escoger la opción Utilizar diseño personalizado. Caso contrario, elija Usarespacio disponible en dispositivos seleccionados y crear diseño predeterminado. En nuestra instalaciónseleccionaremos esta última opción.

Particionamiento de disco duro

Ahora el programa instalador nos consulta si queremos revisar las particiones creadas. Escoja la opción No y digitela tecla de Enter para proseguir.

Page 77: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Confirmación de particiones creadas

Configuración de parámetros de red Es el turno de la configuración de los parámetros de red. El programa de instalación preguntará si desea configurarlos parámetros de direccionamiento IP en las tarjetas de red con las que cuenta su servidor. En la siguientepregunta escoja Si.

Configuración de red

Para cada tarjeta de red que se tenga instalada se preguntará si la desea activar a tiempo de arranque y qué tipo desoporte IP se va a habilitar en ella. El protocolo IP que hemos abordado en el capítulo 2 es la versión 4, por lo querecomendamos escoger el soporte de IPv4. Presione Aceptar.

Page 78: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Activación de parámetros de la tarjeta de red en eth0

Si usted cuenta con un servidor de Dynamic Host Configuration Protocol (DHCP) en su red para la asignacióndinámica de direcciones IP, seleccione la opción Configuración de IP dinámica. De lo contrario deberá asignar ladirección IP de manera manual seleccionando la opción Configuración manual TCP/IP.

Configuración de dirección IP y máscara de red

La siguiente pantalla nos pide el ingreso de parámetros de red adicionales como la puerta de enlace (gateway), DNS primario y DNS secundario. Continúe presionando Aceptar.

Configuración de puerta de enlace y DNS

A continuación debemos bautizar nuestro servidor con un nombre de host o hostname. Se debe considerar que unnombre host correcto tiene la forma nombre.dominio. Su administrador de red sabrá decirle que nombre de hostusar. En caso de no contar con uno, ingrese un nombre ficticio ya que luego es posible cambiarlo. Escoja Aceptarpara continuar.

Page 79: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Configuración de nombre de host

Huso horario, contraseña de root y paquetes En la siguiente pantalla, seleccione el huso horario de su región y presione Aceptar para continuar.

Selección de huso horario

Es hora de especificar la contraseña que será usada por el usuario con privilegios de administrador de Elastix.Recuerde esta contraseña ya que es una parte crítica para la seguridad del sistema. Debido a la importancia de estepaso, se requiere confirmar la contraseña ingresándola nuevamente. Presione Aceptar para seguir con lainstalación.

Especificando la contraseña de administrador (root)

Page 80: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Formateo y copia de archivos A partir de este momento el programa instalador particionará y formateará el disco duro del servidor y toda lainformación almacenada allí se perderá para siempre.

Formateo del disco duro

Adicionalmente, se copiarán todos los archivos necesarios para correr Elastix hacia el disco duro.

Copiado de archivos al disco duro

Una vez que termina la copia de paquetes al disco duro, el servidor se reiniciará automáticamente.

Reinicio automático y contraseñas varias Permita que el sistema arranque por sí solo asegurándose de no presionar ninguna tecla en la siguiente pantalla.

Page 81: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Pantalla de arranque de Elastix

Luego de cargar programas esenciales para su funcionamiento, Elastix procederá a solicitar contraseñas para loscomponentes importantes que conforman su sistema. Esta fase de ingreso de claves solo se realizará en el primerarranque luego de la instalación. La primera clave que se solicita es la del administrador para la base de datos MySQL. Ingrese una clave y continúecon el botón de Aceptar

Contraseña de administración para MySQL

Usted deberá confirmar la clave anteriormente ingresada para administración de MySQL nuevamente en lasiguiente pantalla.

Page 82: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

Confirmación de contraseña de administración para MySQL

La siguiente contraseña será utilizada para ingresar con privilegios de administrador a la interfaz gráfica de Elastix.Además, esta misma clave será utilizada para ingresar a los componentes FreePBX, VTiger y A2Billing delsistema. Una vez digitada la clave, avance a la siguiente pantalla seleccionando Aceptar.

Contraseña de Elastix y sus componentes

Al igual que en el caso anterior, usted deberá confirmar la clave anteriormente ingresada para Elastix y suscomponentes. Luego de ingresarla nuevamente, presione Aceptar para continuar.

Confirmación de contraseña de Elastix y sus componentes

Page 83: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.1_Instalando_desde_CD.htm[24/11/2011 10:21:54 p.m.]

.

Finalizar la instalación El proceso de instalación culminará cuando usted reciba la pantalla de invitación a ingresar a la consola principaldel servidor, tal como se muestra en la figura siguiente.

Autenticación para ingreso a la consola de Elastix

Para acceder a la consola de Elastix, simplemente ingrese root en el prompt de pbx login. La contraseña es la queusted eligió durante el proceso de instalación.

Anterior Ir a índice Siguiente

Page 84: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.2_Instalando_Elastix_sobre_un_soft-RAID.htm[24/11/2011 10:21:58 p.m.]

Anterior Ir a índice Siguiente

5.2 Instalando Elastix sobre un soft-RAID Una configuración muy útil que Elastix ha heredado de Linux es la posibilidad de agregar tolerancia a fallos dedisco duro por medio de RAID (discos redundantes) por software. Hacer esto nos permite agregar un nivel mínimode redundancia a bajo costo. Generalmente es común configurar RAID nivel 1 o espejo que nos permite tener duplicada la información de lasparticiones en sendos discos duros. El sistema operativo Linux hace que Elastix adicionalmente soporte RAIDniveles 0 y 5. Es importante recalcar que no es estrictamente necesario que todas las particiones sean agregadas alarreglo. Sin embargo, es recomendable que si se tienen 2 discos duros, se haga un espejo de todas las particiones. Un esquema de particionamiento típico en un servidor sin RAID consiste en una partición de 100MB para /boot,una partición de 2GB para la memoria swap y el resto del espacio del disco en una partición para la raíz /. Si sesigue este mismo esquema pero con un arreglo RAID de nivel 1 se deberán crear las tres particiones mencionadasen ambos discos duros. De esta forma, al final se tendrán seis particiones.. La configuración del RAID por software (existe hardware que implementan RAID también) se la realiza durante elproceso de instalación del Elastix. En el menú de Tipos de Particionamiento debemos escoger la opción de Creardiseño personalizado. Aquí es donde tendrá la oportunidad de crear las particiones de tipo RAID y luego losdispositivos RAID que agrupan a estas particiones. Para empezar la instalación de Elastix con RAID por software, empecemos con la instalación de Elastix de manerahabitual.

Pantalla de instalación inicial

Al igual que en el proceso de instalación común se deberá seleccionar el idioma del proceso de instalación y el tipode teclado de acuerdo al idioma.

Particiones del disco duro

Page 85: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.2_Instalando_Elastix_sobre_un_soft-RAID.htm[24/11/2011 10:21:58 p.m.]

Dentro de poco el programa instalador mostrará una pantalla preguntando el tipo de particionamiento que se va arealizar.

Opciones de tipo de particionamiento

Aquí usted debe elegir la opción Crear diseño personalizado y asegurarse de que ambos discos duros del servidorestén listados y seleccionados. La pantalla de particionamiento mostrará el listado de discos duros con lasparticiones que se vayan creando.

Herramienta muestra discos duros aún sin particionar

El primer paso será crear todas las particiones de tipo RAID para lo cual se elige la opción Nuevo.

Page 86: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.2_Instalando_Elastix_sobre_un_soft-RAID.htm[24/11/2011 10:21:58 p.m.]

Creando una partición RAID

En la pantalla siguiente se llenarán los siguientes parámetros:

- Punto de montaje: No importa que opción se escoja aquí, ya que se deshabilitará cuando se elija softwareRAID en el campo siguiente.

- Tipo de sistema de archivos: Seleccione software RAID- Unidades admisibles: Escoja un disco a la vez (seleccionándolo con la barra espaciadora).- Tamaño: Especifique el espacio en el disco duro que será reservado para esta partición.- Forzar a partición primaria: No seleccionar.

Cree tres particiones en cada uno de los discos. Para el tamaño escriba 100 para la partición que luego seráasignada al directorio /boot y 2000 para la partición que luego será asignada a la partición tipo swap. Para lapartición que luego será asignada al directorio raíz o /, escriba 1 y seleccione la opción ocupar todo el tamañodisponible. Esto hará que esta partición ocupe el resto del espacio en el disco duro.

Una vez llenados los parámetros seleccione Aceptar. A medida que vaya creando las particiones se irán mostrandoen la pantalla como se muestra a continuación.

Partición tipo RAID por software en disco hda

Cuando se hayan creado las seis particiones (tres en cada disco duro), se debería tener un listado como el que semuestra debajo. Para nuestro ejemplo hemos usado un disco duro de 8GB de tal modo que la única diferencia debeser el tamaño en la última partición.

Particiones de RAID por software

Page 87: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.2_Instalando_Elastix_sobre_un_soft-RAID.htm[24/11/2011 10:21:58 p.m.]

En la figura anterior se aprecia que el particionamiento es exactamente igual para los dos discos duros.

Dispositivos RAID El siguiente paso es la creación de los dispositivos RAID en sí. Para ello se selecciona la opción de RAID.

Creación de arreglo RAID

Ahora debemos crear los dispositivos RAID y que asociaran a las particiones en cada disco que serán replicadas.Para tal efecto debemos crear tres dispositivos accediendo a la pantalla de Crear un dispositivo RAID y llenandolos parámetros de la manera siguiente:

- Punto de montaje: Escriba /boot para el primer dispositivo RAID, no escriba nada para el segundodispositivo RAID (ya que será de tipo swap) y escriba / para el tercer dispositivo.

- Tipo de sistema de archivos: Seleccione ext3 para el primer dispositivo RAID, swap para el segundodispositivo y ext3 para el último.

- Nivel de RAID: Seleccione RAID1 para los tres dispositivos.- Miembros del RAID: Escoja el par de particiones que han sido creadas en cada uno de los discos duros

respectivamente. Estas particiones se replicarán entre sí. En nuestro caso hemos elegido hda1 del primerdisco duro con hdb1 del segundo disco duro para el dispositivo RAID que será montado como /boot. De lamisma forma hemos apareado hda2 con hdb2 para el dispositivo swap y hda3 con hdb3 para el dispositivo /.

- Número de reservas: Este parámetro es aplicable en casos donde se cuenta con más de dos discos duros. Ennuestro caso solo tenemos dos discos así que el valor de 0 es la única opción.

- ¿Desea formatear las particiones?: Este campo debe ser seleccionado. Una vez creados los tres dispositivos RAID, el listado de particiones lucirá muy similar al que se muestra en lafigura siguiente.

Page 88: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_5/5.2_Instalando_Elastix_sobre_un_soft-RAID.htm[24/11/2011 10:21:58 p.m.]

Particionamiento final de RAID nivel 1 por software

Seleccione la opción Aceptar para continuar con la instalación.

Anterior Ir a índice Siguiente

Page 89: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.1_Que_es_Elastix.htm[24/11/2011 10:21:59 p.m.]

Anterior Ir a índice Siguiente

6Introducción a Elastix

Los que dicen “imposible” no deberían interrumpir a los que están intentando-- Proverbio Chino

La intención del presente capítulo es la de hacer un sobrevuelo rápido por Elastix, tratando de aclarar los conceptosbásicos antes de abordar temas más avanzados. Como el lector podrá notar no se trata de un capítulo muy técnicosino más bien informativo a nivel general.

6.1 ¿Qué es Elastix? Elastix es una distribución de software libre de Servidor de Comunicaciones Unificadas que integra diferentestecnologías de comunicaciones en un solo paquete como:

PBXFaxEmailMensajería Instantánea (IM)CalendarioColaboración

Al decir distribución nos referimos al concepto de distro. Es decir, un conjunto de paquetes de software que sedistribuyen juntos en un mismo medio, en este caso un CD, incluyendo el instalador y el sistema operativo. Unavez instalada la distro tendremos un Servidor de Comunicaciones Unificadas listo para producción. Elastix implementa gran parte de su funcionalidad sobre cuatro programas de software muy importantes como son

Page 90: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.1_Que_es_Elastix.htm[24/11/2011 10:21:59 p.m.]

Asterisk, Hylafax, Postfix y Openfire. Estos programas brindan las funciones de PBX, Fax, Email y MensajeríaInstantánea, respectivamente. El sistema operativo se basa en la popular distribución de Linux orientada aservidores llamada CentOS. A continuación se muestra una figura donde se pueden observar los componentes de Elastix y su relación entre sí.

Esquema general de los componentes de Elastix

Anterior Ir a índice Siguiente

Page 91: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.2_Breve_historia_del_proyecto.htm[24/11/2011 10:22:00 p.m.]

Anterior Ir a índice Siguiente

6.2 Breve historia del proyecto Elastix fue creado y actualmente es mantenido por la compañía ecuatoriana PaloSanto Solutions. Elastix fueliberado como software libre por primera vez en Marzo de 2006. Inicialmente no se trataba de una distro sino másbien de una interfaz para mostrar registros de detalles de llamadas para Asterisk (CDRs). Fue recién a finales deDiciembre de 2006 cuando se lo lanzó como una distribución que contenía diversas herramientas administrablesbajo una misma interfaz Web y que llamó la atención por su usabilidad. Desde entonces hasta la fecha Elastix no ha parado de crecer en popularidad, habiendo superado en 2010 su primermillón de descargas.

Galardones En 2007 el proyecto estuvo nominado en 2 categorías para los premios Community Choice Awards (CCA) deSourceForge y volvió a ser nominado en 2008 y 2009. En Febrero de 2011 recibió el premio a Mejor Producto delaño 2010 otorgado por la compañía de medios TMC, quienes además publican la revista Internet Telephony.

Anterior Ir a índice Siguiente

Page 92: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.3_Caracteristicas_Elastix.htm[24/11/2011 10:22:01 p.m.]

Anterior Ir a índice Siguiente

6.3 Características de Elastix Es difícil enlistar todas las características de Elastix debido a que constantemente se añaden más funcionalidades.Sin embargo, las más sobresalientes basados en Elastix 2.0 son las siguientes:

PBX

Voicemails vía Web o emailGrabación de llamadasIVR completo y altamente flexibleParqueo de llamadasColas de atenciónSoporte de síntesis de vozIdentificación de llamadasHorarios de atenciónProvisión automática de teléfonos vía WebCreación de lotes de extensionesSoporte para video vía H.263 y H.264Detección automática de hardware de telefoníaServidor DHCP embebidoReporte de detalle de llamadas (CDRs)Tarifación con reportación de consumo por destinoReporte de uso de canales por tecnología (SIP, ZAP, IAX, Local, H323)

Soporta protocolos SIP, IAX, H323, MGCP, iLBC, entre otrosSoporta codecs ADPCM, G.711 (A-Law & μ-Law), G.722, G.723.1 (pass through), G.726, G.729, GSM,iLBC, entre otrosSoporte para interfaces análogas FXS/FXOSoporte para interfaces digitales E1/T1/J1 (PRI/BRI/R2)Soporte para grupos de troncalesFollow-me, grupos de ringado, paging, DISA, Call back, PINes de seguridad, entre otros

Fax

Servidor de Fax administrable desde WebVisor de Faxes integrado con descargas en PDFIntegración fax-a-emailEnvío de fax vía WebControl de acceso para clientes de faxCapacidad de integración con WinprintHylafax para permitir imprimir-a-fax desde Windows.

Page 93: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.3_Caracteristicas_Elastix.htm[24/11/2011 10:22:01 p.m.]

Email

Servidor de Email multi-dominio administrable vía WebSoporte para SMTP salienteConfiguración de email relayCliente de Email basado en WebSoporte para cuotas en las cuentas de emailFuncionalidad de listas de distribución vía Mailman

Mensajería instantánea (IM)

Servidor de mensajería instantánea basado en OpenFire integradoLlamada vía PBX a usuarios conectadosConfiguración completamente basada en WebInterconexión simultánea a Yahoo, MSN Messenger, GTalk, ICQ, entre otrosSoporta conexiones server-to-server para compartir usuariosReporte de sesiones de usuariosSoporte para pluginsSoporte para LDAP

Calendario

Interfaz de calendario vía WebRecordatorios de vozEnvío de invitaciones a eventos vía emailExportación de calendario a formato iCalendar

Colaboración

Libreta telefónica (Phone Book) con capacidad para click-to-callFuncionalidad de CRM integrada vía vTigerCRMSoporte para teleconferencias de audio configurable vía WebFuncionalidad de conferencias Web vía Addons

Call Center

Soporte para agentes con logon/logoffMarcación predictivaFormularios genéricos para ingreso de datosDisponibilidad de reportes detallados por agente

Page 94: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.3_Caracteristicas_Elastix.htm[24/11/2011 10:22:01 p.m.]

General

Ayuda en línea embebidaInterfaz Web con soporte multi-lenguajeVisualización del sistema vía DashboardConfiguración de fecha/hora/uso horarioConfiguración de parámetros de redConfiguración de usuarios y permisosConfiguración de respaldosConfiguración de temas o skinsActualización centralizada de softwareApagado y encendido remoto vía WebVisualización del sistema en tiempo real vía Operator Panel

Anterior Ir a índice Siguiente

Page 95: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.4_Licenciamiento.htm[24/11/2011 10:22:01 p.m.]

Anterior Ir a índice Siguiente

6.4 Licenciamiento Elastix es software libre distribuido bajo la licencia GPL versión 2. Es decir que puede ser usado, copiado,estudiado, modificado y redistribuido libremente según los lineamientos de esta licencia. Para acceder al texto completo de la licencia el lector puede seguir el siguiente vínculo. http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt

Anterior Ir a índice Siguiente

Page 96: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.5_Elastix.org_Sitio_oficial_del_proyecto.htm[24/11/2011 10:22:02 p.m.]

Anterior Ir a índice Siguiente

6.5 Elastix.org: Sitio oficial del proyecto El principal recurso al que puede acceder el usuario en busca de información acerca de Elastix es el sitio Weboficial del proyecto ubicado en http://www.elastix.org En este sitio el usuario puede encontrar herramientas de soporte útiles como:

ForosWikiChat en vivoSuscripción a listas de correoLinks a descargas

Foros Una de las herramientas más importantes en el sitio Web Elastix.org son los foros. Los foros son muy activos ypara participar en ellos basta registrarse gratuitamente como usuario. Sin duda esta es una buena manera de buscarsolución a problemas comunes y los desarrolladores de Elastix suelen visitar esta herramienta a la caza de posiblesbugs. Sin embargo, el foro es un lugar público así que antes de participar hay que tener en cuenta algunas reglas deetiqueta de foros básicas.

Antes de preguntar en el foro busque si su problema ha sido resuelto antes. La mayoría de problemascomunes ya han sido reportados antes. Si vuelve a preguntar es posible que no le contesten adecuadamente,recuerde que es un foro público.

Los foros se encuentran organizados de cierta manera. Se debe tratar en todo momento de añadir un nuevocomentario a la categoría correcta. Caso contrario se puede desorganizar el foro y el nuevo comentario podríaser ignorado.

Use un lenguaje adecuado para no herir la susceptibilidad de nadie. Si su mensaje contiene lenguaje subidode tono, amenazante o mal intencionado, su mensaje puede ser eliminado permanentemente. La amabilidades un buen ingrediente si desea que otras personas colaboren con su problema.

El foro no es un espacio publicitario.

No adjunte imágenes o archivos pesados. Si necesita subir un archivo mayor a 2 MB trate de subirlo a otroservidor y simplemente copie el vínculo.

Use un título de mensaje relevante y si en algún momento la discusión cambia de tópico, abra otro mensajepara tratar el nuevo tema. Esto ayudará a tener el foro más legible.

Anterior Ir a índice Siguiente

Page 97: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.6_La_interfaz_Web_de_Elastix.htm[24/11/2011 10:22:04 p.m.]

Anterior Ir a índice Siguiente

6.6 La interfaz Web de Elastix Finalmente llegó el momento de ingresar a la interfaz Web de Elastix. Bueno, realmente no creo que el lector hayallegado hasta aquí sin haber ingresado antes a la interfaz de administración Web (por lo menos para curiosear),pero quería decirlo de esta manera para expresar la importancia de este momento. La interfaz Web de administración es el componente que define a Elastix. Sin este componente Elastix no fuera loque es, ya que uno de los objetivos del producto es la facilidad de uso. A menos que se trate de algunaconfiguración personalizada desde aquí es posible administrar prácticamente todo. Se puede utilizar cualquier navegador de Internet para acceder a esta interfaz. Sin embargo, dado que el equipo dedesarrollo de Elastix usa principalmente Firefox para sus pruebas, recomendamos el uso de este navegador. Para ingresar debemos apuntar a la dirección IP del servidor Elastix desde el navegador y veremos una pantallacomo la siguiente.

Pantalla de ingreso a la interfaz Web de administración

Al momento de instalación el sistema generó de manera automática un usuario llamado “admin”. Este usuario tieneprivilegios de administrador y nos servirá para ingresar por primera vez. Notar que el nombre de usuario seencuentra todo en minúsculas. La contraseña para ingresar es la misma que se ingresó durante el proceso deinstalación (ver capítulo 5). Una vez validado el nombre de usuario y contraseña el sistema nos mostrará la interfaz de administración. Loprimero que veremos será el Dashboard que es básicamente una pantalla de resumen con algo de estadística deuso de recursos y estado actual de los procesos más importantes del sistema.

El dashboard de Elastix

Page 98: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.6_La_interfaz_Web_de_Elastix.htm[24/11/2011 10:22:04 p.m.]

Lo siguiente es personalizar un poco la interfaz a nuestras necesidades. Algunas sugerencias son: asegurarnos queel idioma a utilizar sea el Español, que la fecha y hora del sistema, así como el huso horario, se encuentrencorrectos, e inclusive podríamos jugar un poco cambiando el look-and-feel de la interfaz. Todo esto se puede hacerdesde el menú “System -> Preferences”.

Preferencias del sistema

Anterior Ir a índice Siguiente

Page 99: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.7_Configuracion_de_red.htm[24/11/2011 10:22:05 p.m.]

Anterior Ir a índice Siguiente

6.7 Configuración de red Usualmente la primera cosa importante que se debe configurar luego de ingresar al equipo por primera vez son losparámetros de red debido a que por omisión Elastix usa un servidor DHCP para obtener una dirección IP y esto noes lo ideal si vamos a montar un servidor de comunicaciones unificadas. Lo deseable es usar una dirección IPestática. La configuración de los parámetros de red puede hacerse desde el menú “Sistema -> Red”. Aquí podremosconfigurar dos cosas: los parámetros generales de red y los parámetros asociados con cada una de las tarjetas dered que el servidor tenga instaladas, incluyendo las que vienen embebidas en la placa madre o mainboard.

Configuración de parámetros de red

Para editar los parámetros generales de red damos clic en el botón “Editar Parámetros de Red” que aparece en laparte superior de la pantalla anterior. Esto nos conducirá a otra pantalla que se muestra a continuación.

Configuración de parámetros básicos de red

A continuación se explica el significado de cada uno de los campos solicitados.

Host: Nombre del Servidor, por ejemplo: pbx.example.comPuerta de Enlace: Dirección IP de la Puerta de Enlace (Gateway)DNS Primario: Dirección IP del Servidor de Resolución de Nombres (DNS) PrimarioDNS Secundario: Dirección IP del Servidor de Resolución de Nombres (DNS) Secundario o Alternativo.

Para editar los parámetros asociados con cada tarjeta de red debemos dar clic el nombre de dicha interfaz. Ennuestro ejemplo daremos clic donde dice “Ethernet 0” y seremos conducidos a la siguiente pantalla.

Page 100: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.7_Configuracion_de_red.htm[24/11/2011 10:22:05 p.m.]

Edición de los parámetros asociados con una tarjeta de red

Como podemos observar aquí podemos cambiar la asignación de IP de DHCP a Estática que es lo que queríamos.

Anterior Ir a índice Siguiente

Page 101: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

Anterior Ir a índice Siguiente

6.8 Sobrevuelo por la interfaz de administración Web deElastix La interfaz Web de Elastix es una aplicación completa de administración del servidor de comunicacionesunificadas escrita en su mayoría en lenguaje PHP. En esta sección haremos un sobrevuelo de la funcionalidad más importante que podemos administrar desde estainterfaz. Además explicaremos cómo se encuentran organizados los menús y módulos con los que cuenta Elastix.

Menús y módulos La interfaz Web de Elastix se encuentra organizada en menús. Así tenemos los menús de primer nivel como:Sistema, Agenda, Email, Fax, PBX, IM, etc., y también tenemos los menús de segundo nivel, también llamadossub-menús. Un menú se puede entender como un contenedor que sirve para organizar la interfaz de Elastix. Un módulo es cambio es un componente de Elastix que nos ofrece algún tipo de funcionalidad. Los módulos soncontenidos por menús o sub-menús para de esta forma ser organizados dentro de la interfaz Web y que el usuariopueda acceder a ellos navegando entre los menús. En el siguiente ejemplo se puede observar que el módulo “Fecha/Hora” se encuentra contenido dentro del menú (osub-menú) “Preferencias”, el cual a su vez se encuentra contenido dentro del menú “Sistema”. La ubicación delmódulo puede entonces ser referida como “Sistema Preferencias Fecha/Hora”.

Ejemplo de menú, sub-menú y módulo

En ocasiones un módulo puede estar contenido dentro de solo un menú como en la siguiente figura.

Page 102: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

Otro ejemplo de menú y módulo

Nota: Es importante tener presente el concepto de módulo y menú, especialmente si se está interesado enmodificar el código de Elastix para realizar alguna personalización.

Navegando por la interfaz Web A continuación navegaremos por la interfaz Web de Elastix, explicando brevemente el significado de cada menú ymódulo. Cada menú de primer nivel aparecerá encabezando la tabla y cada submenú aparecerá en negritas.

Nota: Es importante mencionar que en el siguiente listado sólo se incluyen los menús que se instalan pordefecto. Es decir que no se incluyen menús que se instalan a través de Addons como el módulo de CallCenter o el de Web Conference.

System Dashboard Dashboard es una especie de escritorio

donde el usuario puede ver un resumen dela actividad en Elastix como sus últimosemails, voicemails, faxes, y citas decalendario. El usuario administrador tieneuna interfaz diferente donde además puedemonitorear el rendimiento del sistema yotras funciones útiles con solo añadirapplets.

Network Configuración de parámetros de red Network Parameters Especificar dirección IP y máscara de red,

gateway, nombre de host, servidores DNS,entre otros.

DHCP Server Habilitar el servidor DHCP embebido queviene con Elastix

DHCP Client List Mostrar lista de clientes DHCP conectados Assign IP Address to Host Asignar dirección IP a un cliente especifico

User Management Administración de usuarios de Elastix Groups Especificar grupos de usuarios Users Administrar usuarios y asignarlos a grupos.

También permite asociar cuentas de email yextensiones telefónicas a los usuarios

Page 103: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

Group Permissions Configuración de los permisos de acceso alos diferentes módulos para un grupodeterminado

Shutdown Apagar o reiniciar el servidorHardware Detector Detección de hardware telefónicoUpdates Actualización de paquetes de software

Packages Listado de paquetes con la opción deinstalar o actualizar

Repositories Configuración de los repositorios en base alos cuales se realizan las actualizaciones

Backup/Restore Generar respaldos y restituir informaciónpara el servidor Elastix

Preferences Especificar las varias preferencias delsistema

Language Cambio del idioma de toda la interfaz Webde Elastix

Date/Time Cambio de la fecha, hora y zona horaria delservidor

Themes Cambio de los temas (skins) para darle a lainterfaz de Elastix un look diferente

Currency Cambio del símbolo de la divisa que semuestra en los reportes de tarifación

Dashboard Applet Admin Selección de los applets incluidos en elDashboard del sistema

Agenda Calendar Agendar eventos en formato calendario que

inclusive pueden generar llamadastelefónicas automáticas

Address Book Libreta de direcciones para contactosRecordings Grabación de mensajes que se pueden

asociar con eventos agendados en el móduloCalendar

Email Domains Creación de dominios de email. Elastix

soporta múltiples dominiosAccounts Administración de cuentas de email y

asignación de cuotas de espacio en discoduro

Relay Configuración de relay permite usar Elastixpara enviar email desde otras redes

Webmail Cliente de email basado en Web víaRoundcube

Antispam Habilitar detección de correo SPAM y

Page 104: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

especificar la sensibilidadRemote SMTP Configurar salida de emails por medio de

un servidor SMTP remotoEmail list Añadir soporte para listas de distribución

(mailing lists) vía Mailman

Fax Virtual Fax Administración de faxes virtuales

Virtual Fax List Listado de extensiones de fax virtuales querecibirán faxes en formato PDF vía email

New Virtual Fax Creación de extensiones de fax nuevas Send Fax Envío de fax desde la interfaz misma como

texto simple o documento adjuntoFax Master Establecimiento de una dirección email que

recibirá notificaciones del funcionamientodel fax

Fax Clients Configuración de permisos de acceso paraaplicaciones clientes de fax

Fax Viewer Visualización de faxes en formato PDFEmail Template Configuración de plantilla de email que se

enviará cada vez que arribe un fax

PBX PBX Configuration Aplicación FreePBX embebida permite la

mayoría de configuraciones a nivel decentral telefónica

Operator Panel Permite la visualización de extensiones,troncales y colas en uso en tiempo real

Voicemail Listado de voicemails. Se debe haberasociado previamente al usuario con unaextensión telefónica para poder verlo

Monitoring Listado de grabaciones telefónicas. Se debehaber asociado previamente al usuario conuna extensión telefónica para poder verlo

Endpoint Configurator Permite provisionar un gran número deteléfonos en corto tiempo

Conference Generar teleconferencias de audioBatch of Extensions Permite crear un gran número de

extensiones en corto tiempoTools Acceso a varias herramientas útiles

Asterisk-Cli Ejecución de comandos del CLI Asterisk File Editor Edición de archivos de texto Text to Wav Conversión de texto a audio

Flash Operator Panel Alternativa de panel de operador basado enflash.

Page 105: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

VoIP Provider Configuración de troncales VoIP conplantillas para ciertos proveedores

IM OpenFire Interfaz embebida para administrar el

servidor mensajería instantánea llamadoOpenfire

Reports CDR Report Reporte de detalles de llamadas (CDRs) con

opciones de filtradoChannel Usage Reporte de uso de canales muestra gráficos

por diferentes tipos de tecnología como SIPe IAX

Billing Especificación de preferencias de tarifación Rates Establecer tarifas dependiendo de la troncal

y del prefijo telefónico Billing Report Tarifación histórica con opciones de

filtrado. Destination Distribution Visualización de gráfico de pastel de la

distribución para destinos por costo,duración y número de llamadas

Billing Setup Configuración de las troncales habilitadaspara la tarifación y tarifa por defecto

Asterisk Logs Reporte del sistema de Asterisk (log) conopciones de filtrado

Graphic Report Visualización de datos generales dellamadas entrantes y salientes en formatográfico para extensiones, troncales y colas

Summary by Extension Resumen de llamadas entrantes, salientes ysu duración por cada extensión con reportegráfico

Extras vTigerCRM Permite integración de Elastix con

funcionalidad de CRMCalling Cards Brinda funcionalidad de tarjetas de llamadas

vía A2BillingDownloads Listado de descargas recomendadas

Softphones Aplicaciones de softphones disponibles Fax Utilities Aplicaciones de fax disponibles Instant Messaging Aplicaciones de mensajería instantánea

(IM) disponibles

Page 106: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.8_Interfaz_de_administracion_Web_de_Elastix.htm[24/11/2011 10:22:07 p.m.]

Addons Available Listado de módulos disponibles para

extender la funcionalidad de ElastixInstalled Listado de módulos instalados

Anterior Ir a índice Siguiente

Page 107: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.9_Administracion_de_usuarios.htm[24/11/2011 10:22:08 p.m.]

Anterior Ir a índice Siguiente

6.9 Administración de usuarios Como ya vimos antes en este mismo capítulo, Elastix crea por omisión un usuario llamado “admin” que poseeprivilegios de administrador del sistema. Este usuario puede parecer todo lo que necesitamos en un principio peroElastix nos da la posibilidad de crear nuevos usuarios con distintos niveles de privilegios, permitiéndonos de estemodo que usuarios diferentes al administrador accedan a la interfaz pero con privilegios limitados. Por ejemplo, podríamos crearle un usuario al recepcionista telefónico para que pueda tener acceso al panel deoperador y contestar, parquear o transferir llamadas de una manera amigable. También podríamos crearle unusuario al departamento de auditoría para que tenga acceso a diferentes reportes como el detalle de llamadas ypueda ver el consumo telefónico hacia destinos internacionales. Podríamos también crearle un usuario aldepartamento de ventas para que puedan tener acceso al CRM integrado. En general Elastix nos proporciona un poderoso y flexible sistema de permisos que nos permitirá crear un usuarioinclusive a cada empleado de la empresa usuaria de Elastix.

Grupos de usuarios Todo usuario de la interfaz Web de Elastix debe pertenecer a un grupo. Por ejemplo, el usuario “admin” quehemos usado antes pertenece a un grupo llamado “administrator”. Este grupo tiene acceso a todos los menús deElastix. Elastix viene con 3 grupos creados por omisión: administrator, operator y extension. Como se puede deducir asimple vista estos grupos sirven para crear usuarios con privilegios de administrador, operador y extensión,respectivamente.

Administración de grupos

Como podemos ver en la figura anterior también es posible crear nuevos grupos de usuarios. Cada grupo deusuarios tiene asociado una matriz de permisos que explicaremos más adelante. Del mismo modo es posiblecambiar la matriz de permisos asociada a los grupos creados por omisión. Es por esto que párrafos más arribahablábamos de un sistema de permisos flexible.

Permisos de grupo Cada grupo de usuarios tiene una matriz de permisos que asocia el grupo de usuarios con los módulos a los cualesdicho grupo tendrá acceso. De este modo podemos configurar una matriz personalizada para cada necesidad,

Page 108: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.9_Administracion_de_usuarios.htm[24/11/2011 10:22:08 p.m.]

únicamente seleccionando los módulos adecuados. Esta matriz de permisos se configura desde “Sistema Administrar Usuarios Permisos de Grupo”.

Administración de permisos de grupo

Creación de usuarios Ahora que ya se han explicado los conceptos de grupos de usuarios y permisos de grupo procederemos a crear unnuevo usuario para la interfaz Web de Elastix. El módulo de usuarios se encuentra ubicado en “Sistema Administrar Usuarios Usuarios”. Allí veremos ellistado de usuarios activos así como también un botón con la etiqueta “Crear Nuevo Usuario”. Damos clic en dichobotón y accederemos a la siguiente pantalla.

Pantalla de creación de nuevo usuario

A continuación una breve explicación del significado de cada uno de los campos.

• Login: El nombre de usuario (username). No debe contener espacios en blanco.• Nombre: El nombre completo del usuario. Por ejemplo “Juan Pérez”.• Contraseña: La clave de acceso• Confirmar Contraseña: Se debe introducir nuevamente la clave de acceso para verificar.• Grupo: El grupo de usuarios al cual pertenecerá el usuario.• Extensión: La extensión de PBX que se asociará al usuario. De este modo cuando el usuario ingrese a la

interfaz podrá ver sus voicemails, grabaciones, detalles de llamadas y otra funcionalidad relacionada con suextensión.

• Usuario de Webmail: El nombre de usuario de correo electrónico creado en el propio Elastix.

Page 109: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_6/6.9_Administracion_de_usuarios.htm[24/11/2011 10:22:08 p.m.]

• Dominio de Webmail: El nombre de dominio del servidor de correo electrónico.• Contraseña de Webmail: La clave de la cuenta de correo electrónico.• Reingrese contraseña de Webmail: Se debe introducir nuevamente la clave de la cuenta de correo

electrónico para propósitos de verificación.

Anterior Ir a índice Siguiente

Page 110: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.1_Creando_una_extension.htm[24/11/2011 10:22:10 p.m.]

Anterior Ir a índice Siguiente

7Configuración Básica de PBX

Educación es elevar al hombre al nivel de su tiempo-- José Martí

La característica de PBX es una de las más importantes de Elastix. En este capítulo explicaremos cómo configuraruna PBX básica usando solamente la interfaz Web de Elastix. Una vez terminada la configuración de la PBX podremos hacer llamadas entre extensiones y hacer uso de algunascaracterísticas interesantes como voicemail o música en espera. En los siguientes capítulos aprenderemos cómo conectar esta PBX al mundo exterior para poder utilizarla en lapráctica.

7.1 Creando una extensión Definir y editar extensiones es probablemente la tarea más común realizada por un administrador de PBX. En laversión 2.0 de Elastix es posible la creación de cinco tipos de dispositivos o tecnologías soportadas para definiruna extensión: SIP, IAX2, DAHDI, “Custom” y Virtual. Para crear una “Nueva extensión” debemos ingresar al Menú “PBX”. Por defecto se accede a la sección “PBXConfiguration”. En esta sección escogemos del panel izquierdo la opción “Extensiones”. Ahora podremos crear unanueva extensión. Primero escoja el dispositivo de entre las opciones disponibles:

Page 111: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.1_Creando_una_extension.htm[24/11/2011 10:22:10 p.m.]

Creando nueva extensión

Generic SIP Device: El SIP es el protocolo estándar para teléfonos IP y ATAs. La mayoría de teléfonos IPsoportan SIP.

Generic IAX2 Device: IAX es el protocolo “Inter Asterisk Exchange”, un nuevo protocolo soportadoactualmente por algunos dispositivos.

Generic ZAP Device: Este dispositivo está asociado a los canales DAHDI. Es un dispositivo de hardwareconectado al servidor Elastix.

Other (Custom) Device: Custom nos permite escribir directamente una entrada en los archivos deconfiguración y por ende esta entrada debe estar en formato de extensión entendible por Asterisk. Puedetambién ser utilizado para relacionar una extensión a un número “externo”. Por ejemplo, para encaminar laextensión 211 a número 1-800-555-1212, se puede crear una extensión “Custom” con número 211 y en lacaja de texto del campo “dial” se puede ingresar: Local/18005551212@outbound-allroutes.

None (virtual exten): Añade la capacidad de crear una extensión virtual.

A continuación nos aparecerá un formulario que varía un poco dependiendo de lo que hayamos escogidopreviamente. Nosotros supondremos que el usuario ha escogido SIP pues es lo más común.

Page 112: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.1_Creando_una_extension.htm[24/11/2011 10:22:10 p.m.]

Formulario de creación de nueva extensión SIP

Como podemos observar se pueden configurar aquí muchas cosas interesantes pero no todos los datos sonnecesarios para conseguir una extensión funcional así que explicaremos sólo los más importantes.

User Extension: Debe ser único. Éste es el número que se puede marcar de cualquier otra extensión. Puedeser de cualquier longitud, pero convencionalmente se utiliza una extensión de tres o cuatro cifras.

Display Name: Es el nombre del Caller ID para que las llamadas de este usuario puedan ser identificadascon un nombre. Sólo debe ingresar el nombre, no la extensión.

Secret: Esta es la contraseña usada por el dispositivo de telefonía para autenticarse contra el servidor deAsterisk que viene en Elastix. Esto es configurado generalmente por el administrador antes de entregar elteléfono al usuario y generalmente no se requiere que lo conozca el usuario. Si el usuario está utilizando unsoftphone, entonces necesitará saber esta contraseña para configurar su software.

Configuración de teléfono IP Para probar si la extensión creada hasta aquí funciona correctamente debemos configurar un teléfono IP para que seregistre en el servidor Elastix (con las credenciales de acceso creadas). Si el lector desea probar esto ahora puederemitirse al capítulo 9 de la presente obra, donde se explica en extenso cómo configurar tanto un teléfono IP físicocomo un softphone instalado en un computador.

Anterior Ir a índice Siguiente

Page 113: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.2_Configuraciones_generales.htm[24/11/2011 10:22:11 p.m.]

Anterior Ir a índice Siguiente

7.2 Configuraciones generales En esta sección se configuran parámetros generales del sistema Elastix en lo que tiene que ver con telefonía. Para acceder a la configuración general debemos ir al menú “PBX Configuración General”. Allí nos aparecerá lasiguiente pantalla.

Formulario de modificación de configuraciones generales

A continuación se explicarán las opciones de dicha pantalla. Opciones del comando dial: Explicaremos esto más al detalle en breve.

Page 114: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.2_Configuraciones_generales.htm[24/11/2011 10:22:11 p.m.]

Opciones para “Company Directory” “Find users in the Company Directory by”: El directorio de una empresa se puede escuchar marcando *411 ó #cuando se escucha un IVR. Esta opción configura de qué modo se ubicarán los usuarios en el directorio. Existen 3maneras: deletreando las 3 primeras letras del apellido, deletreando las 3 primeras letras del nombre, y deletreandolas 3 primeras letras del apellido y nombre al mismo tiempo. “Announce Extension”: Activa el mensaje que reproduce: “Por favor manténgase en la línea mientras transfierosu llamada a la extensión XXX”. Es decir, menciona la extensión a donde se va a transferir la llamada. Esto es útilen casos donde el llamante no conoce previamente la extensión a la cual se le va a transferir, como por ejemplocuando marca una opción (Ej. Opción 3) para ser transferido a un representante de ventas. En estos casos puede serútil que el llamante sepa la extensión a la que fue transferido para poder recordarla en futuras llamadas y saltarse elIVR. “Operator Extension”: Aquí se debe ingresar la extensión del operador, la cual será el destino si un llamantepresiona el cero “0”. Éste destino podría ser una extensión, un grupo de extensiones o inclusive un númerotelefónico externo. “Security Settings”: Permite a anónimas llamadas SIP ser conectadas. El valor por omisión es “no”. “Online updates”: Permite revisar por actualizaciones disponibles. El valor por omisión es “yes”.

Opciones del comando Dial Tal como se observa en la figura anterior la mayoría de ocasiones este campo se llena con las letras “tr”.Realmente aquí se han ingresado dos opciones, la opción “t” y la opción “r”, lo que significa que la persona querecibe la llamada puede transferirla y que adicionalmente se enviará un tono de timbrado de vuelta al llamante. A continuación se enlistan todas las opciones disponibles.

A(X): Toca un anuncio a la persona llamada, usando X como archivo.D(dígitos): Envía la secuencia de dígitos DTMF luego que el destino ha contestado.h: Permite a la persona llamada colgar enviando el dígito “*”.H: Permite al llamante colgar enviando el dígito “*”.r: Envía un tono de timbrado a la parte llamante.T/t: Permite a la parte (llamante/llamada) transferir llamadas.W/w: Permitir a la parte (llamante/llamada) iniciar la grabación de la llamada en curso, el código pordefecto para iniciar la grabación de llamada es “*1”.

Anterior Ir a índice Siguiente

Page 115: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.3_Configuracion_de_colas.htm[24/11/2011 10:22:13 p.m.]

Anterior Ir a índice Siguiente

7.3 Configuración de colas Las colas consisten en grupos de usuarios para los cuales se definen ciertas políticas (o estrategias) principalmenteen lo que tiene que ver con llamadas entrantes. Las colas pueden ser creadas como una extensión más. Los usuariosde las colas pueden ser estáticos, llamados “miembros” (es decir que tienen un número de extensión fijo) o usuariosdinámicos, llamados agentes (es decir que pueden ingresar a la cola desde cualquier extensión). Una política o estrategia define la manera cómo se distribuyen las llamadas entrantes a la cola entre los miembros oagentes. Las políticas de cola que soporta Asterisk al momento son las siguientes:

Sonar todos: Timbra las extensiones de todos los agentes hasta que uno conteste. Esta es la opción pordefecto.Agente con última llamada más antigua: Timbra la extensión del agente que menos recientemente contestóuna llamada de esta cola.Agente con menos llamadas: Timbra la extensión del agente que menos llamadas haya atendido en estacola.Aleatorio: Timbra las extensiones de manera aleatoria.Con memoria: Timbra la extensión de cada agente de manera secuencial, pero recuerda cuál fue el agenteque atendió la última llamada para proceder a timbrar la próxima llamada al siguiente agente.Linear: Timbra las extensiones de los agentes en el orden especificado, ó en el orden en que los agentes sehan logoneado a la cola. Wrandom: Timbra las extensiones de los agentes de manera aleatoria pero utilizando una penalidad comomedida de probabilidad.

Para configurar una cola en Elastix tenemos que ir al Módulo PBX y escoger en el menú llamado “Colas”. Para añadir una nueva cola deberemos llenar el siguiente formulario.

Page 116: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.3_Configuracion_de_colas.htm[24/11/2011 10:22:13 p.m.]

Formulario para añadir nueva cola

Número de Cola:Este es el número que debe ser discado para ingresar a la cola. Nombre de Cola:Un nombre para la cola. Este es usado únicamente para propósitos de identificación. Contraseña de Cola:A una cola se le puede poner una clave. Cualquier llamante que intente ingresar a la cola debe digitar dicha clave. Prefijo del nombre del CID:Como un agente puede iniciar sesión y atender llamadas de varias colas al mismo tiempo, es útil colocarle unprefijo al Caller ID de las llamadas para que cuando el agente reciba la llamada entrante en su teléfono, puedasaber a través de este CallerID que la llamada pertenece a una cola determinada. Agentes Fijos:Estos son las extensiones que siempre atenderán llamadas que lleguen a la cola. Agentes Dinámicos:Aquí se especifican los miembros que no usan una extensión fija para atender las llamadas de la cola, sino quedeben iniciar sesión en la cola y atienden desde cualquier extensión que esté disponible. Anuncio de Agente:Este es un anuncio que es reproducido al agente antes de que una llamada le sea transferida. Esto es útil cuando losagentes no tienen detección de Caller ID en su teléfono y se desea saber que una llamada proviene de una colaespecifica.

Page 117: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.3_Configuracion_de_colas.htm[24/11/2011 10:22:13 p.m.]

Clase de Música en espera:Hace posible la selección de qué clase de música será reproducida al llamante mientras está en la cola a la esperade que un agente lo atienda. Tiempo máximo de espera:Es el tiempo máximo que una llamada permanecerá en la cola antes de ser desviada la llamada al destino en casode fallo. La acción a tomar después de este tiempo es configurada en la sección “Destino en caso de fallo”. Llamantes Máximos:Es el máximo número de personas permitidas a esperar en la cola. Si este número es alcanzado, las llamadas enexceso serán desviadas al destinado configurado en “Destino en caso de Fallas”. Entrar si vacía:Si se desea que los llamantes ingresen a una cola vacía (sin agentes), entonces hay que cambiar este parámetro a“yes”. Esto no es recomendado. Salir cuando vacía:Se cambia a “yes” si se desea no dejar ingresar más llamadas en el momento en que haya salido el ultimo agentede atención en la cola. Estrategia de timbrado:Hay 7 tipos de estrategia de timbrado, la cuales fueron explicadas anteriormente:

- Sonar todos- Agente con última llamada más antigua- Agente con menos llamadas- Aleatorio- Con memoria- Linear- Wrandom

Tiempo de espera de agente:El tiempo en que le sonará la extensión a cada agente miembro de la cola antes de enviar la llamada a otro agente. Reintentar:El tiempo que el sistema va a esperar luego de haber hecho sonar todas las extensiones de todos los agentesmiembros antes de volver a llamarlos a todos. Wrap-up-time:Después de una llamada exitosa, indica el número de segundos antes de declarar al agente libre y enviarle unanueva llamada, El valor por defecto es 0. Grabación de llamadas:Opción de grabar las llamadas entrantes a la cola. Destino en caso de falla:Este el destino si una llamada de la cola no pudo ser atendida.

Page 118: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.3_Configuracion_de_colas.htm[24/11/2011 10:22:13 p.m.]

Anterior Ir a índice Siguiente

Page 119: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.4_IVR_y_sistema_de_grabacion.htm[24/11/2011 10:22:14 p.m.]

Anterior Ir a índice Siguiente

7.4 IVR y sistema de grabación

Grabación de mensaje de bienvenida Antes de Crear un IVR es necesario tener un mensaje ya grabado que será reproducido cuando una llamada esatendida por dicho IVR. Usted tiene 2 opciones para este fin: grabar el mensaje desde su propia extensión o cargarun archivo de audio grabado anteriormente. La primera opción sin duda es la más cómoda puesto que podemos grabar desde el mismo teléfono en un tiempomuy corto. Sin embargo la segunda opción nos da la posibilidad de cargar un archivo de audio producido enestudio. Existen compañías que se dedican a brindar estos servicios de grabación de voces para IVRs ydependiendo de nuestro presupuesto pueden incluir voces profesionales, música de fondo, efectos de sonido, entreotras características. Para acceder a este módulo diríjase al Menú “PBX”, aparecerá por defecto la sección “Configuración PBX”, en elpanel izquierdo escoja la opción “Grabaciones del sistema”.

Grabaciones del sistema

Como ya se mencionó la primera opción nos permite grabar el audio directamente desde una extensión yafuncional. Para esto ingresamos el número de extensión desde el cual queremos realizar la grabación en el recuadroque dice “Si desea realizar y comprobar grabaciones desde su teléfono, por favor, escriba aquí su extensión”, eneste caso usaremos la extensión 201 y damos clic sobre el botón Ir. Luego de hacer esto, Asterisk estará esperando nuestra grabación en la extensión 201, para continuar descolgamosel teléfono de la extensión ingresada y marcamos *77, se escuchara un pitido el cual indicará que podemoscomenzar a vocalizar nuestro mensaje, para indicarle al sistema que hemos concluido el mensaje presionamos latecla # (numeral), caso contrario no se grabará el mensaje.

Page 120: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.4_IVR_y_sistema_de_grabacion.htm[24/11/2011 10:22:14 p.m.]

Para revisar nuestra grabación desde el mismo teléfono marcamos *99, a continuación comenzará a reproducir elmensaje que acabamos de grabar. Si usted se encuentra conforme con el resultado, el siguiente paso será asignar unnombre a la grabación en el recuadro correspondiente y luego dar clic sobre el botón “Guardar”. La segunda opción que tenemos es cargar una grabación creada en otro medio, para ello debemos tener un archivode audio con un formato soportado por Asterisk. En el mismo menú anterior haga clic sobre el botón“Examinar...”, buscamos nuestro archivo, luego procedemos a darle un nombre a esta grabación. Finalmente damosclic en “Guardar”.

Configurar un IVR de bienvenida El IVR nos permite recibir una llamada entrante y reproducir un mensaje de bienvenida. Además podemos tener unmenú interactivo por teclado telefónico, a través de los 10 dígitos, y los símbolos # (numeral) y * (asterisco). Conesto es posible encaminar la llamada hacia otro destino o nuevamente hacia el IVR que envió el anuncio. Para acceder al módulo “IVR” diríjase al Menú “PBX” y aparecerá por defecto la sección “Configuración PBX”.En el panel izquierdo escoja la opción “IVR”. Para grabar un mensaje de bienvenida, como ya se explicó en la sección anterior, debe dirigirse al menú de“Grabaciones del sistema” y proceder a la grabación de un mensaje. Para la creación de un IVR no es necesario llenar todos los campos, pues para nuestro caso (un IVR debienvenida), no necesitaremos opciones. Los campos necesarios son los siguientes:

Cambiar nombre: Etiquetar el IVR con un nombre distintivo.

Tiempo de espera: Tiempo de espera (en segundos) antes de encaminar la llamada a un operador después dehaber sido reproducido el mensaje pregrabado.

Habilitar marcación directa: Opción que permite a quien llama marcar una extensión interna directamente sin tener que esperar a que el operador conteste.

Anuncio: Es el anuncio o mensaje de bienvenida que se grabó anteriormente. Aparecerá una lista con todoslos mensajes disponibles.

A continuación se debe proceder a configurar cuáles serán los destinos de las llamadas de acuerdo con el dígito queel llamante presione en su teléfono. Por ejemplo, generalmente el dígito 0 (cero) hace que la llamada sea enviada ala extensión del operador. Es posible configurar destinos para los números del 0 al 9.

Page 121: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.4_IVR_y_sistema_de_grabacion.htm[24/11/2011 10:22:14 p.m.]

Formulario de creación de IVR

Entre las opciones del menú disponibles, en la parte izquierda existe un casillero donde se debe ingresar el dígitocorrespondiente a la opción del IVR. Luego debe escoger cuál será el destino de la llamada. Aquí usted podráseleccionar entre varios módulos disponibles en FreePBX, ya sea enviar la llamada a un cola de atención yadefinida, a otro IVR, a un grupo de timbrado, a un extensión específica, etc. Finalmente grabamos el IVR haciendo clic en el botón de “Guardar”

Anterior Ir a índice Siguiente

Page 122: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.5_Salas_de_conferencias.htm[24/11/2011 10:22:16 p.m.]

Anterior Ir a índice Siguiente

7.5 Salas de conferencias Elastix puede administrar dos tipos de cuartos de conferencia: Los cuartos de conferencia permanentes y loscuartos de conferencia temporales. El primer tipo se puede administrar bajo el menú “PBX PBX Configuration Conferences”, mientras que el segundo se puede administrar bajo el menú “PBX Conferencias”. Los cuartos de conferencia no son otra cosa que una especie de extensión virtual en la que a través de ella sepueden interconectar varias llamadas al mismo tiempo, dando con esto la ilusión de estar en una conferencia conmuchas personas conversando al mismo tiempo. Un cuarto de conferencia permanente es aquel que tiene un numero definitivo preasignado. Por ejemplo,supongamos que queremos crear el cuarto 88999 y asignarlo al Gerente de Operaciones. De ahora en adelante lasreuniones telefónicas de los lunes por las mañanas se pueden realizar simplemente marcando 88999 cuando lleguela hora pactada y todos los participantes saben que ese número de cuarto no cambiara de lunes a lunes. Un cuarto de conferencia temporal se crea, como es obvio, para fines temporales. Por ejemplo la empresa va aparticipar de una exposición de productos en el extranjero y quiere agendar una serie de reuniones entre losproveedores y asesores externos para que se pongan de acuerdo en diferentes tópicos. Por lo tanto se decideasignar un cuarto de conferencia para cada asesor con el fin de que ellos mismos coordinen las conferencias quecrean necesarias. Lógicamente no queremos que estos cuartos sean permanentes sino más bien que expiren luego dela feria ya que ellos no son trabajadores permanentes de la compañía.

Listado de conferencias

En el presente apartado explicaremos cómo administrar conferencias temporales. Al ingresar al módulo de conferencias se podrá observar todas las conferencias concurrentes. Para visualizarconferencias pasadas o futuras debe seleccionar la opción correspondiente en el recuadro de “Estado” y haciendoclic en “Mostrar”. Además se provee un filtro usado para los nombres de las conferencias. Para poder eliminar una o varias conferencias debemos seleccionarlas y dar clic sobre el botón “Eliminar”. Si desea agregar una nueva conferencia de clic sobre el botón “Nueva Conferencia”.

Page 123: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.5_Salas_de_conferencias.htm[24/11/2011 10:22:16 p.m.]

Creación de nueva conferencia

Los campos requeridos para agregar una conferencia son:

Nombre de la Conferencia: Necesario para identificar la conferenciaNúmero de la conferencia: Se provee un número aleatorio para la conferencia. Usted puedecambiarlo si no está siendo usado por otra conferenciaTiempo Inicio (PST/PDT): Tiempo de inicio de la conferenciaMáximo Participantes: No se podrán invitar más participantes una vez se completo el número máximode participantes.

Para ver los detalles sobre una conferencia puede dar clic sobre el nombre de la conferencia. A continuación se mostrará la manera de administrar las conferencias temporales. Para administrar una conferenciaconcurrente de clic sobre el enlace de participantes correspondiente a dicha conferencia. Para invitar a alguien a la conferencia debe escogerlo de la lista proporcionada (lista de extensiones disponibles) ydar clic sobre el botón “Llamada a invitar”. Deberá esperar hasta que se conteste la llamada. Una vez que haya invitado a alguien a la conferencia irán apareciendo en el reporte. Si desea silenciar a uno ovarios invitados selecciónelos en la columna “Callado” y de clic sobre este botón (“Callado”). Además puede expulsar de la conferencia a uno o varios invitados seleccionándolos en la columna “Botar” y declic sobre este botón (“Botar”). Si desea expulsar a todos los invitados de la conferencia de clic sobre “Botar a Todos”. Si alguien a quien invitó no se muestra en la lista de invitados o alguien a quien expulsó todavía se muestra, de clicen el botón “Actualizar”. Este botón también actualizará el tiempo que lleva cada invitado en la conferencia. Note que una vez de clic sobre el botón “Callado” se actualizará el Estado del invitado, los estados posibles son:Muted (Callado), UnMuted (No Callado).

Page 124: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.5_Salas_de_conferencias.htm[24/11/2011 10:22:16 p.m.]

Para regresar a la interfaz de administración de todas las conferencias de clic en “Cancelar”.

Anterior Ir a índice Siguiente

Page 125: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.6_Parqueo_de_llamadas.htm[24/11/2011 10:22:17 p.m.]

Anterior Ir a índice Siguiente

7.6 Parqueo de llamadas Un lote de llamadas es una extensión virtual con música en espera. Es decir que si se llama a esta extensiónoiremos música en espera. A esta acción se le llama parquear una llamada. Esta característica es muy útil cuando atendemos una llamada y debemos transferirla a una extensión de la quetodavía no sabemos el numero destino. Por ejemplo, ingresa una llamada importante para el gerente de la empresay él no está en su oficina. Dada la importancia la operadora tiene que localizarlo, así que mientras lo busca puedetransferir al llamante en un lote de parqueo para que espere confortablemente con música en espera. Claro, muchosdirán que simplemente se lo pudo haber puesto on hold pero esto ocuparía la extensión del teléfono de recepciónimpidiendo que nuevas llamadas puedan ser atendidas por la recepcionista. Una vez localizado al esquivo gerentese le puede comunicar que tiene una llamada parqueada en el lote 3434, por ejemplo. Luego, el mismo gerentepuede des-parquear dicha llamada y reiniciar la conversación desde su propia extensión o la extensión más cercana.

Configuración de un nuevo lote de parqueos

Habilitar característica de aparcamiento:Seleccionando esta opción con un visto se habilitará la funcionalidad de parqueo de llamadas. Extensión de aparcamiento:Indica la extensión a la cual deberá llamarse para enviar una llamada al parqueo. Generalmente indica el primerslot de canales de parqueo. Dependiendo del número de slots de aparcamientos va a depender cuántas extensionesse tengan para este fin. Cantidad de aparcamientos:Indica el número de slots disponibles para parquear llamadas. De éste número depende cuantas extensiones setengan disponibles para aparcar una llamada.

Page 126: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.6_Parqueo_de_llamadas.htm[24/11/2011 10:22:17 p.m.]

Tiempo máximo de aparcamiento:El período de tiempo que una llamada puede permanecer parqueada. Si una llamada cumple ese tiempo en elcuarto de parqueo se intentará retornar la llamada a la extensión desde donde se envió el parqueo. Contexto del aparcamiento:Este es el contexto que regirá el comportamiento de las llamadas parqueadas. Por defecto este contiene el contexto“parkedcalls” y no debería ser cambiado. Destination for Orphaned Parked Calls:Sirve para configurar el destino de una llamada cuando esta no puede ser enviada al parqueo y quien envióoriginalmente la llamada tampoco puede ser alcanzado. Los destinos posibles pueden ser: Un anuncio, un IVR,terminar la llamada, una extensión, una cola, una conferencia ó una aplicación personalizada.

Anterior Ir a índice Siguiente

Page 127: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.7_Musica_en_espera.htm[24/11/2011 10:22:19 p.m.]

Anterior Ir a índice Siguiente

7.7 Música en espera En esta sección es posible configurar las categorías de “Música en espera” que estarán disponibles para lasdiferentes colas de atención. El usuario escuchará la reproducción sucesiva de los archivos allí definidos comofondo mientras espera que le atiendan. Enviar archivo WAV o MP3:Simplemente mediante el botón “choose file” se selecciona el archivo (en formato mp3 o wav). Luego se debehacer clic en “Enviar” y debe aparecer el archivo disponible en la lista de archivos de MOH (Music-On-Hold) quese muestran debajo de la opción de cargado de archivo. Es posible ajustar el volumen de los archivos cargados utilizando la opción “Ajuste de volumen” que se encuentraabajo del botón de “Enviar”

Formulario de administración de música en espera

Anterior Ir a índice Siguiente

Page 128: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.8_Panel_de_Operador.htm[24/11/2011 10:22:20 p.m.]

Anterior Ir a índice Siguiente

7.8 Panel de Operador A partir de Elastix 2.0, se ha incorporado el “Elastix Operator Panel” (EOP) que se presenta como una alternativaal existente “Flash Operator Panel” (FOP). La razón por la cual se introdujo el EOP se debe a que la nueva versión del FOP (FOP2) requiere un tipo delicencia que es incompatible con la actual licencia de Elastix (GPL versión 2). De manera general el panel de operador permite visualizar el estado de las extensiones, troncales, colas, cuartos deconferencias y cuartos de parqueo del sistema en tiempo real. Es una aplicación muy útil para una recepcionista.

Para acceder al “Elastix Operator Panel” diríjase al Menú “PBX” y haga clic en la utilidad “Operator Panel”.

Panel de operador Elastix

Adicionalmente, en Elastix 2.0 aún se encuentra disponible el “Flash Operator Panel” en el menú de “PBX” en elsubmenú “Flash Operator Panel”.

Flash Operator Panel

Anterior Ir a índice Siguiente

Page 129: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_7/7.9_Funciones_transferencia_de_llamadas.htm[24/11/2011 10:22:21 p.m.]

Anterior Ir a índice Siguiente

7.9 Funciones de transferencia de llamadas Por omisión en Elastix viene configurada la funcionalidad de transferencia de llamadas de la siguiente forma:

Transferencia ciega Para trasferir una llamada de una manera ciega se debe digitar: ## seguido del número de extensión a donde se vaa transferir la llamada.

Transferencia atendida Para transferir una llamada de manera atendida se debe digitar: *2, seguido de la extensión. Si desea cambiar éstos códigos es necesario dirigirse al menú de “PBX PBX Configuration” y escoger el menúde “Códigos de funcionalidades”. En la sección “Core” usted tendrá las opciones de “In-Call Asterisk AttendedTransfer” e “ In-Call Asterisk Blind Transfer” donde podrá cambiar el código asignado para las transferenciasatendidas y ciegas respectivamente.

Códigos de Características

Anterior Ir a índice Siguiente

Page 130: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.1_Tipos_de_tarjetas_fabricantes.htm[24/11/2011 10:22:22 p.m.]

Anterior Ir a índice Siguiente

8Configuración de hardware

No siempre podemos agradar, pero siempre podemos tratar de ser agradables-- Voltaire

A pesar de que Elastix puede funcionar sin necesidad de hardware telefónico instalado en el mismo servidor, esnecesario su utilización si se requiere conexión directa a ciertos tipos de redes telefónicas como la PSTN. Suinstalación y configuración se simplifica con Elastix gracias a que se dispone de una interfaz Web especializadaque facilita esta tarea. En el presente capítulo nos referiremos básicamente a tarjetas PCI (o PCI express). Sin embargo pueden usarseotros dispositivos para conectarse a la PSTN como es el caso de los gateways, que funcionan a través de IP ochannel banks que pueden inclusive funcionar a través de USB.

8.1 Tipos de tarjetas y fabricantes En este apartado nos referiremos básicamente a tarjetas telefónicas, también llamadas tarjetas de interfaz. Estehardware está disponible tanto para redes telefónicas analógicas como digitales y dentro de cada una de estascategorías existen básicamente las siguientes subcategorías:

AnalógicoFXOFXS

DigitalE1/T1/J1BRI

Page 131: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.1_Tipos_de_tarjetas_fabricantes.htm[24/11/2011 10:22:22 p.m.]

Existen variadas opciones de hardware compatible con Elastix por lo que no tendremos problemas para encontraruna que se adapte a nuestras necesidades. Para facilitar todavía más la elección Elastix cuenta con un programa de certificación de hardware que se encargade someter cada modelo a diversas pruebas para determinar su compatibilidad con Elastix de acuerdo a los criteriosdel programa de certificación. La lista de hardware certificado está disponible de manera pública en el siguiente enlace: http://www.elastix.org/en/product-information/certified-hardware.html Aquí no solo encontraremos tarjetas de interfaz sino también teléfonos IP, gateways, intercomunicadores, channelbanks, cámaras de seguridad y appliances. Cabe resaltar que si un determinado modelo no se encuentra enlistado no necesariamente significa que no escompatible con Elastix. Debido a que el programa de certificación estipula que el proceso de pruebas debe darseúnicamente por solicitud explícita del fabricante, puede darse el caso de que el modelo que estamos buscando nohaya sido propuesto por su fabricante para ser sometido al proceso de certificación.

Anterior Ir a índice Siguiente

Page 132: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.2_Instalacion_de_hardware.htm[24/11/2011 10:22:23 p.m.]

Anterior Ir a índice Siguiente

8.2 Instalación de hardware de telefonía en Elastix Instalar hardware de telefonía en Elastix es una tarea relativamente sencilla. Sin embargo, es necesario tener claroslos conceptos antes de comenzar pues de lo contrario podríamos confundirnos. Para instalar hardware de telefonía en Elastix debemos seguir los siguientes pasos.

1) Instalar el hardware físicamente2) Detectar el hardware a nivel de drivers3) Configurar el hardware a nivel de Asterisk

Cada una de estas tareas se explicará a continuación.

Anterior Ir a índice Siguiente

Page 133: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.3_Instalacion_fisica_tarjeta.htm[24/11/2011 10:22:25 p.m.]

Anterior Ir a índice Siguiente

8.3 Instalación física de una tarjeta Esto no involucra ninguna tarea complicada, solo las precauciones obvias al instalar tarjetas electrónicas en uncomputador, como haber apagado y desconectado completamente el equipo de la toma eléctrica, usar un dispositivode descarga electrostática, entre otras.

Nota: En caso de instalar hardware FXS es muy común que se requiera conectar un cable de poder a latarjeta pues hay que recordar que las interfaces FXS deben proveer potencia eléctrica a los dispositivosque se conecten a ella.

Tarjeta telefónica analógica de tipo modular con 3 puertos FXO y 2 FXS instalados

En la figura anterior podemos observar en la parte inferior derecha el conector tipo molex que sirve para proveer deenergía adicional a la tarjeta en caso de que usemos módulos FXS. Luego de instalar la tarjeta encendemos el equipo y deberíamos verla enlistada a nivel de bus PCI. Como ejerciciopodríamos utilizar el comando lspci antes y después de instalar la tarjeta y ver la diferencia.

Hardware modular Existen fabricantes que diseñan su hardware de manera modular, de tal forma que pueda ser expandible. Losmódulos por tanto no se encuentran soldados sino que pueden ser instalados a presión. Por ejemplo, demos un vistazo a la tarjeta analógica de la siguiente imagen que tiene capacidad de hasta 8 puertos.Se puede observar claramente los módulos y que el fabricante los ha diferenciado: los módulos FXO son de colorrojo y los FXS son de color verde.

Page 134: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.3_Instalacion_fisica_tarjeta.htm[24/11/2011 10:22:25 p.m.]

La misma tarjeta de la imagen anterior a la cual se le ha extraído un módulo FXS

Existen también otro tipo de tarjetas donde inclusive el cancelador de eco es un módulo que se puede instalar apresión. De este modo se puede adquirir la tarjeta con o sin cancelador de eco por hardware.

Anterior Ir a índice Siguiente

Page 135: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.4_Deteccion_de_hardware.htm[24/11/2011 10:22:26 p.m.]

Anterior Ir a índice Siguiente

8.4 Detección de hardware Una vez que la tarjeta ha sido instalada es hora de que los drivers la detecten. El driver de telefonía más importanteen Elastix recibe el nombre de DAHDI (realmente se trata de un conjunto de drivers). No entraremos en muchosdetalles de DAHDI por ahora puesto que la interfaz Web de administración nos permitirá abstraernos de la labor delos drivers. Sin embargo, más adelante explicaremos un poco más a fondo el funcionamiento de DAHDI y cómo serelaciona con Asterisk.

Nota: Cabe mencionar que DAHDI no es el único driver de telefonía existente en Elastix. Si bien lamayoría de fabricantes de hardware de telefonía usan DAHDI (o han integrado sus drivers dentro deDAHDI), existen otros fabricantes que proveen drivers diferentes como es el caso de Sangoma o RhinoEquipment. Estos otros drivers también se encuentran integrados dentro de Elastix.

En las primeras versiones de Elastix la tarea de detectar el hardware se hacia manualmente ejecutando algunoscomandos desde la consola del equipo. Actualmente se cuenta con una interfaz Web que detecta el hardware demanera automática y nos muestra gráficamente el hardware detectado. Esta interfaz se puede acceder desde el menú “System → Hardware Detector”. Para detectar nuevo hardware basta con presionar el botón “Detectar Nuevo Hardware”.

Detección de Hardware Elastix 2.0

En dicho menú se tienen las siguientes opciones:

• “Replace file chan_dahdi.conf”: Esta opción crea un archivo /etc/asterisk/chan_dahdi.conf adicionalmentea los necesarios que se requieren para el sistema DAHDI (/etc/dahdi/modules.conf y /etc/dahdi/system.conf)que será procesado por Asterisk, conteniendo la información de configuración de las tarjetas que sedetecten.

• “Detect Sangoma Hardware”: Esta opción activa el funcionamiento del demónico de “wanrouter” provistopor el fabricante SANGOMA para reconocimiento de su hardware y su integración con los modulos deDAHDI.

• “Detect ISDN hardware”: Esta es una opción heredada de versiones anteriores de Elastix, utilizadaexclusivamente para detección de hardware del tipo “mISDN”. Comúnmente se utiliza esta opción para ladetección de tarjetas BRI de Digium y sus clónicas.

Page 136: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.4_Deteccion_de_hardware.htm[24/11/2011 10:22:26 p.m.]

Para las tarjetas de telefonía analógica y digitales se encuentra disponible la herramienta para configurar el tipo decancelación de eco (basado en software) que se utilizará para cada puerto de la tarjeta. Para configurar elcancelación de eco haga clic en el ícono que parece una rueda. A continuación se ingresará a la configuración particular de la tarjeta mostrando cada uno de los puertos de lamisma y un menú desplegable para la elección del algoritmo requerido por cada puerto. Los algoritmos soportadosson: OSLEC, MG2, KBL, SEC, SEC2.

Nota: El algoritmo más usado es OSLEC. Se puede encontrar más explicación acerca de los canceladoresde eco y OSLEC en el capítulo 13.

Algoritmos de cancelación de eco por puerto

Para las tarjetas de telefonía digital, se encuentra disponible una utilidad para configurar los parámetros desincronización necesarios y particulares para líneas E1 ó T1 en forma gráfica. Para acceder a dicha utilidad debehacer clic en el ícono que tiene la forma de dos conectores. A continuación se ingresará a la configuración particular de la tarjeta con un menú de opciones desplegables. Laelección de los valores de las opciones dependerá del tipo de interfaz digital y el servicio que su proveedor detelefonía le haya instalado.

Configuración de parámetros de sincronización en tarjeta telefonía digital

En la sección siguiente se explicarán con más detalles todos los parámetros necesarios para la sincronización paratarjetas digitales. Una vez ejecutada la acción de reconocimiento de hardware, Elastix crea archivos de configuración con lainformación suministrada y añadiendo información adicional que la considera como “usualmente” correcta,denominada “por defecto”.

Page 137: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.4_Deteccion_de_hardware.htm[24/11/2011 10:22:26 p.m.]

A partir de ésta configuración por defecto el usuario podría modificar ciertos parámetros más específicos para suambiente, para que el hardware de telefonía se ajuste a su situación particular. Estas configuraciones a bajo nivelse explicarán en la siguiente sección.

Nota: Al momento de escribir este libro si se presiona el botón para detectar hardware TODAS las tarjetasserán re-detectadas y su configuración por defecto re-escrita. Si ya se había configurado una tarjetapreviamente esta configuración será re-escrita. No se olvide de hacer los respaldos necesarios.

Anterior Ir a índice Siguiente

Page 138: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.5_Configuracion_del_hardware.htm[24/11/2011 10:22:28 p.m.]

Anterior Ir a índice Siguiente

8.5 Configuración del hardware de telefonía a nivel deAsterisk Hasta este momento el hardware que hemos configurado no se encuentra relacionado con Asterisk de ningunamanera (a menos que se haya presionado el botón de “Replace chan_dahdi.conf”). Asterisk por omisión no sabe si hardware nuevo ha sido detectado por DAHDI a menos que se le hayaespecificado a través del archivo /etc/asterisk/chan_dahdi.conf. Hay que entender que Asterisk y DAHDI son dospaquetes de software separados y no saben nada el uno del otro a menos que nosotros los comuniquemosexplícitamente. Veamos a continuación un vista simplificada de cómo se comunican Asterisk y DAHDI.

Diagrama simplificado de cómo se relaciona Asterisk con DAHDI

Podemos ver en el diagrama anterior que Asterisk se relaciona con DAHDI a través de un módulo (módulo deAsterisk) llamado chan_dahdi.so y que este módulo necesita del archivo /etc/asterisk/chan_dahdi.conf para sabercómo comunicarse con DAHDI correctamente.

Nota: Más adelante entraremos en detalles acerca del archivo /etc/dahdi/system.conf mostrado en eldiagrama anterior.

Antes de entrar en detalles de configuración del archivo chan_dahdi.conf debemos mencionar que una manerasencilla y automática de configurar nuestro hardware a nivel de Asterisk es presionar el botón “Replacechan_dahdi.conf”. Como el lector podrá suponer esta acción reemplaza el archivo chan_dahdi.conf por unogenérico. Sin embargo, en la mayoría de los casos la configuración escrita en este archivo sólo nos será de utilidadcomo ejemplo o punto de inicio debido a que Elastix no tiene manera de conocer cómo queremos agrupar los

Page 139: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.5_Configuracion_del_hardware.htm[24/11/2011 10:22:28 p.m.]

canales telefónicos u otros parámetros que dependen de nuestro ambiente específico y que se configuran en dichoarchivo. A continuación explicaremos cómo configurar adecuadamente el archivo chan_dahdi.conf

Configuración del archivo chan_dahdi.conf Asterisk cuenta con un módulo llamado chan_dahdi.so que sirve para comunicarse con los drivers de DAHDI y deesta manera conectar Asterisk con hardware telefónico. Este módulo se configura a través del archivochan_dahdi.conf En el archivo chan_dahdi.conf básicamente se configura la señalización de los canales de voz y serelacionan los canales de Asterisk con los circuitos o líneas telefónicas definidos en la configuración de losdrivers. Estos canales se pueden agrupar en lo que se conoce como troncales.

Nota: La configuración de los drivers de DAHDI reside principalmente en el archivo/etc/dahdi/system.conf. Este archivo se escribió automáticamente cuando realizamos la detección dehardware desde la interfaz Web.

Es decir que si tengo 15 circuitos o líneas telefónicas que terminan en hardware telefónico de mi servidor los puedocontrolar desde Asterisk y troncalizarlas. Por ejemplo podría dividir esas líneas en 3 troncales debido a que micliente tiene 3 departamentos: ventas, soporte y financiero. Veamos primero un archivo chan_dahdi.conf sencillo para ver los parámetros más importantes y despuéscontinuaremos explicando algunos de estos parámetros. [trunkgroups] [channels]context=from-pstnsignalling=fxs_ls ; trunk #0group=0language=escallprogress=nocontext=from-pstnchannel=1-5 ; trunk #1group=1language=escallprogress=nocontext=from-pstnchannel=6-10 ; trunk #2group=2language=escallprogress=nocontext=from-pstn

Page 140: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.5_Configuracion_del_hardware.htm[24/11/2011 10:22:28 p.m.]

channel=11-15

Como vemos arriba hemos configurado tres troncales. Cada troncal comienza con la palabra group y se le asignaun identificador numérico. Por lo general se empieza con el número cero. Dentro de cada troncal se pueden repetir los valores globales (es decir los que se encuentran en el encabezado,fuera de la definición de las troncales) y estos valores sobrescriben a los anteriores. Por ejemplo, se podríasobrescribir la señalización para una troncal específica. Algunos parámetros importantes

signaling Este parámetro define la señalización de cada canal o grupo de canales. Lo más común que veremos para circuitosanalógicos será fxs_ls y para circuitos digitales pri_cpe. A continuación la tabla de posibles valores para esteparámetro.

em: E & M Immediate Startem_w: E & M Wink Startem_e1: E & M CAS signalling for E1 linesfeatd: Feature Group D (The fake, Adtran style, DTMF)featdmf_ta: Feature Group D (The real thing, MF (domestic, US)) through a Tandem Access pointfgccama: Feature Group C-CAMA (DP DNIS, MF ANI)fgccamamf: Feature Group C-CAMA MF (MF DNIS, MF ANI)featdmf: Feature Group D (The real thing, MF (domestic, US))featb: Feature Group B (MF (domestic, US))fxs_ls: FXS (Loop Start)fxs_gs: FXS (Ground Start)fxs_ks: FXS (Kewl Start)fxo_ls: FXO (Loop Start)fxo_gs: FXO (Ground Start)fxo_ks: FXO (Kewl Start)pri_cpe: PRI signalling, CPE sidepri_net: PRI signalling, Network side (for instance, side that provides the dialtone)sf: SF (Inband Tone) Signallingsf_w: SF Winksf_featd: SF Feature Group D (The fake, Adtran style, DTMF)sf_featdmf: SF Feature Group D (The real thing, MF (domestic, US))sf_featb: SF Feature Group B (MF (domestic, US))e911: E911 (MF) style signalling. Originating switch goes off-hook, far-end winks, originating sends KP-911-ST, far-end gives answer supervision, Originating-end sends KP-0-ANI-STThe following are used for Radio interfaces:fxs_rx: Receive audio/COR on an FXS kewlstart interface (FXO at the channel bank)fxs_tx: Transmit audio/PTT on an FXS loopstart interface (FXO at the channel bank)fxo_rx: Receive audio/COR on an FXO loopstart interface (FXS at the channel bank)fxo_tx: Transmit audio/PTT on an FXO groundstart interface (FXS at the channel bank)

Page 141: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.5_Configuracion_del_hardware.htm[24/11/2011 10:22:28 p.m.]

em_rx: Receive audio/COR on an E&M interface (1-way)em_tx: Transmit audio/PTT on an E&M interface (1-way)em_txrx: Receive audio/COR AND Transmit audio/PTT on an E&M interface (2-way)em_rxtx: same as em_txrx (for our dyslexic friends)sf_rx: Receive audio/COR on an SF interface (1-way)sf_tx: Transmit audio/PTT on an SF interface (1-way)sf_txrx: Receive audio/COR AND Transmit audio/PTT on an SF interface (2-way)sf_rxtx: same as sf_txrx (for our dyslexic friends)

switchtype Este parámetro es para circuitos digitales y especifica el tipo de switch PRI usado. Lo más común es national yeuroisdn, dependiendo de en qué país nos encontremos claro está. Este dato lo debe proporcionar la compañíatelefónica así que sintámonos en la libertad de preguntar. Los valores posibles son los siguientes.

national: ISDN nacional tipo 2ni1: ISDN nacional tipo 1dms100: Nortel DMS1004ess: AT&T 4ESS5ess: Lucent 5ESSeuroisdn: EuroISDNqsig: Protocolo usado en ISDN

Anterior Ir a índice Siguiente

Page 142: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.6_Configuracion_de_interfaces_digitales.htm[24/11/2011 10:22:29 p.m.]

Anterior Ir a índice Siguiente

8.6 Configuración de interfaces digitales utilizando losarchivos de configuración DAHDI La herramienta de detección de hardware basada en Web que incorpora Elastix nos permite detectar el hardware demanera sencilla. Sin embargo, a pesar de que la herramienta puede configurar exitosamente el hardware digital enmuchos casos, hay que tener en cuenta que la herramienta realiza su trabajo asumiendo parámetros por defecto quepueden ser personalizados de acuerdo al ambiente real de su servidor. Los cambios necesitan ser hechos directamente en los archivos de configuración, por lo tanto se requerirá tenerconocimiento más profundo a este nivel.

Nota: En este apartado nos referiremos básicamente a circuitos T-Carrier y E-Carrier basados en losdrivers de DAHDI.

Configuración de drivers DAHDI El hardware de telefonía que instalemos en el servidor Elastix debe ser reconocido en primera instancia por losdrivers (Ej.: DAHDI) y luego ser activado en la configuración de Asterisk. DAHDI lee su configuración principalmente del archivo /etc/dahdi/system.conf. Para interfaces digitales, en el archivo /etc/dahdi/system.conf se deben definir los spans. Un span es ungrupo de canales digitales. Usualmente un span representa un puerto digital de la tarjeta. Por ejemplo, si la tarjetacontiene 4 puertos E1 entonces usualmente deberíamos definir 4 spans, uno por cada puerto. Un span define en una sola línea, la cual tiene el siguiente formato. span=(spannum),(timing),(LBO),(framing),(coding)

SpannumEs un identificador numérico único para etiquetar el span. Se debe empezar con el número 1 e ir incrementandoeste identificador secuencialmente de uno en uno. TimingEs un dígito que define la forma en la cual se manejará la sincronización del span. Los posibles valores son lossiguientes. Valor Significado0 NO usar el span (telco) como fuente de sincronización.

DAHDI proveerá la sincronización y la enviará al otro lado.Esto es más común cuando se conecta a través de este spanuna PBX antigua a la cual hay que proveerle sincronización.

Page 143: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.6_Configuracion_de_interfaces_digitales.htm[24/11/2011 10:22:29 p.m.]

Normalmente si nos conectamos a una compañía telefónica nodeberíamos tener ningún span con este valor de timing

1 Usar el span (telco) como fuente primaria de sincronización2 Usar el span (telco) como fuente secundaria de sincronización3,4,5,……,n Usar el span (telco) como fuente de sincronización tercera,

cuarta, quinta, etc…

Nota: Solo el valor 0 puede ser repetido. Los demás valores del uno en adelante NO se deben repetir. LBO (Line Build Out)Es un dígito que representa la longitud del cable entre la tarjeta y el equipo (modem) provisto por la compañíatelefónica. Casi siempre se puede dejar en 0 sin problemas. Sin embargo si tenemos un cable muy largo habrá querevisar la tablita siguiente. Valor Longitud del cable o nivel de atenuación0 0 dB / 0 - 133 pies1 133 - 266 pies2 266 - 399 pies3 399 - 533 pies4 533 - 655 pies5 -7.5 dB6 -15 dB7 -22.5 dB

FramingComo recordaremos, los protocolos de comunicación digital T-Carrier y E-Carrier dividen la información enframes, donde cada frame transporta un número determinado de timeslots. Estos frames pueden ser de diferentesformatos y eso es lo que se define aquí. Los valores posibles para T1 son d4 o esf, mientras que para E1 son cas o ccs. CodingEs necesario codificar la información enviada para hacerla menos susceptible a errores. Esto es así porque la propiadata se suele usar como fuente de sincronización (o reloj) y si se transmiten tramas largas de ceros (largossegmentos sin variación de voltaje) se puede perder dicha sincronización. Para evitar esto se codifica la data paraevitar transmitir estas tramas largas de ceros. Por ejemplo la codificación b8zs significa Bipolar with 8 ZerosSubstitution. Los valores posibles para T1 son ami o b8zs, mientras que para E1 son ami o hdb3. En E1 también se puedenecesitar añadir chequeo de errores crc4 (Control de Redundancia Cíclica de 4 bits o Cyclic Redundancy Check 4-bits). Luego de realizar los cambios en el archivo system.conf será necesario reiniciar el demónico de DAHDI. Si todoha sido correctamente configurado, DAHDI cuenta con el comando “lsdahdi”, el cual al ser ejecutado desde laconsola del sistema operativo mostrará las tarjetas configuradas y el respectivo estado de sus canales. Si a pesar de que todo se encuentre correctamente configurado y se reciban señales de alarma o errores debeasegurarse que no exista algún problema con el cableado físico o que el proveedor de la troncal digital tenga un

Page 144: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.6_Configuracion_de_interfaces_digitales.htm[24/11/2011 10:22:29 p.m.]

problema en su lado.

Anterior Ir a índice Siguiente

Page 145: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.7_Detalles_de_DAHDI.htm[24/11/2011 10:22:30 p.m.]

Anterior Ir a índice Siguiente

8.7 Detalles de DAHDI En esta sección se detallan los nombres de los archivos importantes que vienen como parte del sistema DAHDI yuna breve descripción de cada uno de ellos.

Archivos de configuración Archivos DAHDI Descripción/etc/dahdi/system.conf Archivo de configuración

donde se define la señalizaciónde cada uno de los puertos detelefonía.

/etc/asterisk/chan_dahdi.conf Este archivo realmente es unarchivo de configuración deAsterisk que se utiliza paradecirle a Asterisk con quécanales DAHDI se debecomunicar y cómo.

/etc/dahdi/init.conf Este es un archivo utilizado porel script de inicio de DAHDI(/etc/init.d/dahdi).

/etc/dahdi/modules Este archivo contiene losnombres de los drivers deDAHDI que se encuentranpresentes en nuestro sistema.(recordemos que DAHDI estácompuesto por varios drivers).Este archivo es leido por elscript de inicio de DAHDIpara saber qué drivers debecargar y de este modo nocargar todos los drivers sinosolo los necesarios.

Módulos de kernel de DAHDI

Módulo DAHDI en Kernel Descripcióndahdi.ko Módulo de kernel (driver) que contiene la

funcionalidad principal de DAHDIdahdi_dummy.ko Driver necesario para proveer de una fuente de

timing a Asterisk cuando no tenemos tarjetasinstaladas, debido a que las tarjetas poseen unafuente de timing vía hardware

Módulos de Asterisk de DAHDI

Módulo DAHDI en Asterisk Descripción

Page 146: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.7_Detalles_de_DAHDI.htm[24/11/2011 10:22:30 p.m.]

chan_dahdi.so Módulo de Asterisk que se comunica con losdrivers de DAHDI

app_dahdibarge.so Módulo de Asterisk que provée la aplicaciónDAHDIBarge a nivel de plan de marcado. Estaaplicación sirve para monitorear (escuchar) un canalde DAHDI.

app_dahdiscan.so Módulo de Asterisk que provee la aplicaciónDAHDIScan a nivel de plan de marcado. Estaaplicación sirve para navegar entre canales ymonitorearlos.

Comandos DAHDI

Comando DAHDI Descripcióndahdi_cfg Configura el hardware a partir del archivo de

configuración /etc/dahdi/system.confdahdi_monitor Monitorea los niveles de entrada y salida de un

canal DAHDIdahdi_scan Imprime la configuración de los spans DAHDIdahdi_speed Realiza pruebas de desempeño sobre hardware

DAHDIdahdi_test Prueba si el temporizador de DAHDI está

funcionando correctamentedahdi_tool Muestra el estado de las interfases DAHDI. Muy

útil para hacer depuración.dahdi_genconf Genera de manera automática archivos de

configuración para el hardware DAHDI

Anterior Ir a índice Siguiente

Page 147: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.8_Antes_de DAHDI_.htm[24/11/2011 10:22:31 p.m.]

Anterior Ir a índice Siguiente

8.8 Antes de DAHDI: equipos que usaban Zaptel A partir de Elastix 1.5 el paquete Zaptel fue reemplazado por el paquete DAHDI. Debido a que es un cambiorelativamente reciente es probable que en la práctica nos encontremos con estos equipos que todavía usan Zaptel.Para que podamos configurar adecuadamente dichos equipos en esta sección presentamos un resumen de lasdiferencias más importantes entre estos dos paquetes de drivers.

Algunos cambios de nombre a tener en cuenta Si bien uno de los cambios más obvios de la migración de Zaptel a DAHDI es el cambio de nombre de los canalesde ZAP a DAHDI; existen otros cambios de nombre que son importantes tener en cuenta y que se describen acontinuación.

Cambios en archivos de configuración Archivo DAHDI Archivo Zaptel/etc/dahdi/system.conf /etc/zaptel.conf/etc/asterisk/chan_dahdi.conf /etc/asterisk/zapata.conf/etc/dahdi/init.conf y /etc/dahdi/modules /etc/sysconfig/zaptel

Cambios de nombre de módulos de kernel Módulo DAHDI Módulo Zapteldahdi.ko zaptel.kodahdi_dummy.ko ztdummy.ko

Cambios de nombre de módulos de Asterisk Módulo DAHDI Módulo Zaptelchan_dahdi.so chan_zap.soapp_dahdibarge.so app_zapbarge.soapp_dahdiscan.so app_zapscan.so

Cambios de nombre de algunos comandos Comando DAHDI Comando Zapteldahdi_cfg ztcfgdahdi_monitor ztmonitordahdi_scan ztscan

Page 148: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_8/8.8_Antes_de DAHDI_.htm[24/11/2011 10:22:31 p.m.]

dahdi_speed ztspeeddahdi_test zttestdahdi_tool zttooldahdi_genconf zapconf o genzaptelconf

Anterior Ir a índice Siguiente

Page 149: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.1_Configuracion_softphone.htm[24/11/2011 10:22:33 p.m.]

Anterior Ir a índice Siguiente

9Configuración de teléfono IP

Es difícil despertar a aquel que simula estar dormido-- Proverbio navajo

La configuración de un teléfono IP suele ser bastante sencilla. Como mínimo un teléfono IP necesita 3 valores parafuncionar: El IP del servidor PBX (en este caso el IP del servidor Elastix), el nombre de usuario (comúnmente laextensión) y la contraseña de registro de dicho usuario. Aquí mostraremos al detalle cómo configurar un teléfono IP físico y otro basado en software ya que los softphonesse han vuelto bastante populares en los últimos tiempos. En estos teléfonos se usará tecnología SIP para suconfiguración puesto que es la tecnología más popular en la actualidad, pero tenga la seguridad que laconfiguración de teléfonos soportando protocolo IAX no difiere mucho de lo aquí mostrado. De forma general, eneste libro se usará el protocolo SIP en la mayoría de los ejemplos con excepción de los casos donde los teléfonosno se encuentren conectados dentro de la red local, en cuyo caso será preferible la utilización del protocolo IAX,ya que no es susceptibles a problemas relacionados con la traslación de direcciones IP (NAT). Al final del capítulo se detallará la manera de configurar una gran cantidad de teléfonos IP de manera ágil ysencilla. Este método nos permite pre-configurar los teléfonos desde una herramienta llamada “endpointconfigurator” disponible en Elastix.

9.1 Configuración de softphone Actualmente el uso de teléfonos en software o softphones se ha popularizado en gran medida más que nada por elhecho del ahorro que puede significar al no tener que adquirir teléfonos físicos. El ahorro es mayor mientras másextensiones se requieran, por lo que ésta alternativa es muy común en call centers.

Page 150: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.1_Configuracion_softphone.htm[24/11/2011 10:22:33 p.m.]

Por supuesto antes de empezar a configurar el softphone habrá que crear una extensión desde Elastix. A manera de ejemplo vamos a suponer que se ha creado la extensión 5678 la cual utiliza tecnología SIP comoprotocolo VoIP y su “secret” asignado es “8765”. El softphone que vamos a configurar será el Zoiper que está disponible en versión gratuita y comercial. La versióngratuita es suficiente para que podamos hablar cómodamente de un punto a otro así que basaremos nuestro ejemploen esta versión. Para descargar el Zoiper debemos visitar el sitio http://www.zoiper.com Suponemos que el lector tiene la habilidad suficiente para instalar el software sin problemas. Una vez instalado loejecutamos y aparecerá una ventana como la siguiente.

Pantalla inicial del software ZoIPer

A continuación presionamos el botón con la figura de herramienta y accederemos al menú de opciones. Sedesplegará una pantalla con opciones para configurar nuevas extensiones SIP y también IAX, pues el Zoiper cuentacon soporte para ambos protocolos. En nuestro ejemplo configuraremos una extensión SIP, así que veremos unapantalla como la siguiente.

Configurando una cuenta SIP

Page 151: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.1_Configuracion_softphone.htm[24/11/2011 10:22:33 p.m.]

Llenaremos dicha pantalla con los siguientes datos:

Domain: La dirección IP o nombre de dominio del servidor Elastix.Username: 5678Password: 8765Caller ID Name: El nombre que aparecerá en los teléfonos que reciban nuestras llamadas

Luego de presionar el botón “OK”, volvemos a la pantalla inicial del Zoiper. Para proceder a registrar la extensiónrecientemente configurada en la central Elastix, debemos seleccionar la extensión creada en el combo de la parteinferior y dar clic en el botón “Register”.

Antes de registrar la cuenta SIP

Si Zoiper se registra correctamente observaremos que junto al nombre de nuestra cuenta “Test” aparecerá la palabra“Registered”.

Luego de que la cuenta SIP ha sido registrada

Puede repetir este proceso para configurar otro softphone Zoiper en otra PC utilizando una extensión diferentecreada en el mismo Elastix y luego comprobar que es posible establecer llamadas VoIP entre estas dos extensiones.En el ejemplo la extensión 5678 recibe la llamada de la extensión “2222”.

Page 152: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.1_Configuracion_softphone.htm[24/11/2011 10:22:33 p.m.]

Llamada ingresando a nuestro softphone

Nota: Asterisk ofrece la posibilidad de comprobar el funcionamiento de extensiones recientemente creadasa través de una extensión de “ECO”. Esta extensión contestará automáticamente y reproducirá el mismoaudio que enviemos.

Anterior Ir a índice Siguiente

Page 153: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

Anterior Ir a índice Siguiente

9.2 Configuración de teléfono IP Para configurar un teléfono IP debemos tener en cuenta dos aspectos:

1. Configuración de red2. Registro del dispositivo con el servidor Elastix

Para ilustrar de mejor manera los puntos mencionados utilizaremos a manera de ejemplo un teléfono PolycomSoundPoint IP 330.

El teléfono Polycom 330 que configuraremos

Configuración de red La configuración de red puede realizarse considerando que por defeco el teléfono obtendrá su IP mediante DHCP,pero también es posible configurar un dirección IP fija. Explicaremos los dos métodos. Luego de la configuración IP del equipo, se accesará a la interfaz Web de administración del mismo para completarel proceso ingresando los parámetros restantes.

DHCP Mediante esta opción, el teléfono obtendrá una dirección IP de manera automática. Debe tomar en cuenta que lared debe contar con un servidor DHCP funcional, que es quién asignará en su la dirección IP. Elastix trae disponible un servidor DHCP embebido que se puede activar fácilmente desde la interfaz Web.

Page 154: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

A continuación se detalla cómo verificar en el teléfono IP cuál fue la dirección IP que le fue asignada. Presionar "Menu Status Network TCP/IP Parameters” En la pantalla LCD se mostrará la dirección IP. Anotémosla para luego poder acceder al teléfono desde la interfazWeb.

IP estática Si usted necesita contar con un registro exacto de las direcciones IP de sus teléfonos y/o si desea colocar susdispositivos IP en segmentos específicos de su red, debe utilizar direcciones IP estáticas en sus teléfonos. Paraconfigurar una dirección IP en el teléfono, deberá ingresar los parámetros de IP, máscara de red, gateway y DNSsen un menú diferente. A continuación las instrucciones de cómo ingresar cada uno de ellos. Dirección IP Dado que por defecto el teléfono viene configurado para recibir su dirección IP vía DHCP, a continuaciónmostramos la manera de cambiar dicho comportamiento a uso de IP fijo. En la interfaz del teléfono Presionar"Menu Settings Advanced (ingresar clave. Por omisión es 456) Admin Settings NetworkConfiguration DHCP Client Editar Disabled Phone IP Address" Aquí procederemos a ingresar la dirección IP. Máscara de red Si usted no ingresa una máscara de red adecuada, su teléfono IP no podrá registrarse con su central Elastix. Esosproblemas ocurren con mayor frecuencia cuando los teléfonos IP están dentro de diferentes segmentos de redes quela central Elastix, es ahí donde se debe seleccionar la máscara adecuada. Seleccionar "Subnet Mask” (Ingresar la máscara de red) Puerta de enlace En el caso de que su teléfono se necesite conectar en un segmento de red IP diferente al que se encuentraconectado el servidor Elastix, el teléfono deberá contar con la dirección IP de la puerta de enlace (por lo general esun router) correspondiente, de lo contrario su teléfono no podrá registrarse en la central Elastix. Seleccionar "IP Gateway” (Ingresar la dirección IP de la puerta de enlace) Luego de cualquier cambio debemos seleccionar "Exit" y luego "Save Config". Debemos esperar a que el teléfonotermine de reiniciarse.

Configuración de registro contra el servidor Elastix Esta configuración se la pueda realizar desde el mismo teléfono o desde un navegador Web. En este casoutilizaremos el navegador Firefox.

Page 155: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

Dado que ya conocemos la dirección IP de nuestro teléfono la accedemos desde el navegador Web. En el siguienteejemplo la dirección IP de nuestro teléfono es la 192.168.1.235

Barra del navegador Firefox

Antes de ingresar a la interfaz de configuración Web un cuadro de diálogo nos solicitará el usuario y la clave delteléfono. El usuario y clave de fábrica son “Polycom” y “456” respectivamente.

Diálogo de autenticación vía usuario y contraseña

IP Servidor Elastix Para ingresar los parámetros de registro contra el servidor Elastix, comenzaremos ingresando los parámetros que semuestran en la pestaña “SIP”. En esta pantalla se podrán configurar una parte de los parámetros SIP, como lo son el servidor SIP, es decir ladirección IP de la central Elastix y el “Outbound Proxy” que viene a ser lo mismo en nuestro caso. Laconfiguración adecuada se muestra en la siguiente figura, donde se supone que la dirección IP del servidor Elastixes la 192.168.1.160

Page 156: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

Interfaz Web de configuración de parámetros SIP del teléfono

Debemos tomar en cuenta de que la dirección de la central Elastix puede pertenecer o no a nuestro segmento dered IP, puesto que la central se encuentra en el Internet, igual será posible llegar a ella a través de la puerta deenlace configurada. En esta misma pantalla también es posible cambiar el puerto utilizado para señalización SIP contra la centralElastix. Si usted cambia a otro valor diferente al de omisión (5060 UDP) debe asegurarse que este cambio tambiénhaya sido hecho en la central Elastix.

Extensión Para ingresar los parámetros específicos a la extensión asignada al teléfono IP, seleccione la pestaña de "Lines" yconfigure aquí su extensión como se muestra en la siguiente figura. El parámetro “Auth Password” debe ser igualal parámetro “secret” que se ingresó cuando se creó la extensión en la interfaz Web del Elastix.

Page 157: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

Configuración de la línea SIP

Configuración Opcional En esta sección veremos cómo configurar el Polycom para que muestre la fecha y hora del Elastix. En el menú debemos dar clic en la pestaña "General" y en el campo "SNTP Server" (bajo la sección time) ingresarla dirección IP del servidor Elastix. Adicionalmente debemos seleccionar el valor adecuado de su zona horaria en "GMT Offset"

Page 158: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.2_Configuracion_telefono_IP.htm[24/11/2011 10:22:36 p.m.]

Configuración del servidor de tiempo

Nota: Si al intentar digitar alguna de las extensiones disponibles en la central Elastix (desde el teléfonoque estamos configurando) escuchamos una señal de ocupado aún cuando ni siquiera se han terminado dedigitar todos los dígitos de la extensión destino, revise la opción "Digitmap", dentro de la sección "LocalSettings" dentro del menú "SIP", o en su defecto elimínela por completo.

Cambiando el mapa de dígitos

Anterior Ir a índice Siguiente

Page 159: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Anterior Ir a índice Siguiente

9.3 Utilizando el Endpoint Configurator En ocasiones la instalación de teléfonos IP se complica cuando son muchos y más aún cuando la configuración noes tan trivial como la que se realiza para el softphone. Como ya se mostró en la sección anterior algunos modelosde teléfonos se pueden configurar desde una interfaz Web embebida en el propio teléfono y también existen otrosque se tienen que configurar a través de una sesión telnet. La distro Elastix cuenta con una interfaz que nos permitirá configurar muchos teléfonos de una manera mássencilla y ágil. Esta herramienta recibe el nombre de Endpoint Configurator. El módulo Endpoint Configurator primero realiza un rastreo (scan) de la red o subred que se le suministre. Algo denotar es que cuando se ingresa al módulo, la red o subred por omisión es aquella que se encuentra configurada enla propia central Elastix; el scan que se ejecuta sobre dicho segmento de red obtiene internamente información deMAC e IP de los dispositivos de red conectados.

Rastreando la red en busca de endpoints

Nota: La dirección MAC le sirve al endpoint configurator como identificador único del teléfono. Si se usarala dirección IP ésta podría cambiar con el tiempo, pero con la dirección MAC no ocurre esto.

Luego de obtener la información de todos los endpoints del segmento de red, el módulo de forma inteligente tratade identificar los equipos que pudieran ser teléfonos IP y de la misma forma trata de recabar información acercadel fabricante y modelo para elegir cuáles puede configurar consultando su base de datos interna de modelos deteléfonos. Cuando ya se tiene el grupo de teléfonos a configurar se presenta la información en la interfaz Web de Elastix. Semostrara algo como se ilustra en la figura siguiente.

Page 160: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Listado inicial de teléfonos encontrados en la red. Sin configurar aún.

Como se puede observar en la figura anterior se muestra una lista de todos los teléfonos que se han encontrado enel segmento de red dado y que el Elastix conoce o podrá configurar según su base de datos. Como podrá notar el reporte muestra las columnas Dirección MAC, Dirección IP y Fabricante, las que nosayudarán a reconocer de cual teléfono IP se trata y con esto podremos relacionar mentalmente su ubicación física.

Vista acercada de campos MAC, dirección IP y Fabricante

Luego existen dos columnas llamadas Modelo de Teléfono y Extension de Usuario. Estas columnas sirven paraasociar una extensión (previamente creada en Elastix) con un teléfono físico. En la lista llamada “Modelo deTeléfono” podrá elegir el modelo del teléfono que se desea asociar con la extensión y solo se listaran aquellos queElastix sabe configurar y reconocer. Tener en cuenta que para configurar los teléfonos se deben haber creadospreviamente extensiones desde el menú “PBX PBX Configuration”.

Nota: Una limitante de esta herramienta es que las extensiones deben ser SIP y no están soportadasextensiones de ningún otro protocolo. Actualmente el grupo de desarrollo de Elastix está trabajando enincorporar soporte para otros protocolos.

Configuración de un teléfono ATCOM, modelo AT-530 A continuación explicaremos paso a paso cómo configurar un teléfono marca ATCOM, modelo AT-530. Este es unmodelo de teléfono de bajo costo que soporta tanto SIP como IAX.

Page 161: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Para configurarlo primero elegimos el modelo y la extensión a configurar del listado mostrado en el EndpointConfigurator. Cuando un teléfono es configurado por primera vez mediante este módulo, éste presenta un estatus“No Configurado” lo que significa que todavía la central Elastix no tiene configuración acerca del él.

Línea correspondiente al teléfono AT-530 detectado en la red

Debe elegir la casilla ubicada en el lado izquierdo de la pantalla, y luego presionar el botón “Configurar”.Inmediatamente aparece la ventana de confirmación en la cual si se está seguro se acepta y el proceso deconfiguración empezará. Esto puede tomar algo de tiempo dependiendo del número de teléfonos que haya elegido,en este caso por ser un ejemplo hay solo un teléfono a configurar.

Vista amplificada con los datos del teléfono AT-530

Luego del proceso vamos a ver que el reporte se actualizó y el estatus del teléfono es “Configured withoutincident”. Esto indica que la central Elastix hizo varias cosas.

Primero creó el (o los) archivos de configuración necesarios en la ruta /tftpboot/ (ruta en la centralElastix) y en caso de este ejemplo solo se creó el archivo atc0009455765aa.cfg donde 0009455765aarepresenta la dirección MAC del teléfono.

Segundo creó un registro en la base de datos de Elastix para mantener un historial del teléfono configurado.

Tercero, mediante conexión telnet (solo para los ATCOM), realizó acciones de cargar el archivo deconfiguración al teléfono, guardar al archivo y reiniciar. Por ello usted podrá notar que el teléfono se va hareiniciar.

Teléfono AT-530 configurado

Hay que tener ciertas consideraciones en cuanto a la conexión telnet en los teléfonos ATCOM y es que para poderestablecerse es necesario de un usuario y contraseña que por efectos de simplicidad en Elastix se usan los quevienen por omisión de fábrica. Para el caso del modelo AT-530 son usuario admin con clave admin y para el casodel AT-320 la clave es 12345678.

Page 162: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Regresando a interpretar los Status del teléfono tenemos. Estatus Color DescripciónNo Configurado Naranja No configurado aun por la

central ElastixConfigured without incident Verde La central configuró el

teléfono sin problemasUPDATE: Secrets no equalsin FreePBX and Endpoint

Rojo Es necesario actualizar. Larazón es porque ha cambiadola clave en la central(FreePBX) y en la base deendpoint.db aun se mantienela anterior

Si no hay incidentes entonces ahora nuestro teléfono IP ya esta configurado desde la central Elastix y cuando sedesee cambiar de extensión sólo vamos al endpoint configurator, hacemos un par de clics y listo.

Nota: Existe el botón “Desconfigurar”. La acción que ejecuta éste es sólo a nivel del módulo. La centralElastix borra el registro histórico relacionado con el teléfono IP de la base de su base de datos interna yborra los archivos de configuración relacionados en la ruta /tftpboot/. Esto indica que el teléfono va amantener la configuración que le fue entregada desde la última actualización desde esta herramienta.

Configuración de un teléfono Polycom SoundPoint IP 501 A continuación mostraremos un ejemplo de cómo configurar un teléfono Polycom SoundPoint IP501. Primero elegimos el modelo y la extensión a configurar. Como en el caso del teléfono ATCOM podemos partir deque es la primera vez que se lo va a configurar desde la central Elastix y por ende notamos el Status “NoConfigurado”.

Línea correspondiente al teléfono Polycom detectado en la red

En la parte izquierda vamos a elegir la casilla, y luego presionamos el botón “Configurar”. Inmediatamente aparecela ventana de confirmación en la cual si esta seguro se acepta y el proceso de configuración empezará. Esto puedetomar algo de tiempo dependiendo del número de teléfonos que haya elegido, en este caso por tratarse de unejemplo hay solo un teléfono a configurar.

Vista amplificada con los datos de nuestro teléfono Polycom IP501

Page 163: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Luego del proceso vamos a ver que el reporte se actualizó y el estatus del teléfono es “Configured withoutincident”, esto indica que la central Elastix realizó varias acciones. Primero creo los archivos de configuración necesarios en la ruta /tftpboot/ (ruta en la central Elastix). Estosarchivos para el caso de los teléfonos Polycom se detallan en la tabla abajo mostrada.. Archivo Descripción0004f21aeb17.cfg El 0004f21aeb17 representa la dirección MAC y este archivo es

un encabezado que le indica al teléfono lo que se va a hacerdurante el proceso de actualización y configuración

0004f21aeb17reg.cfg Contiene información de la (o las) extensiones que va haposeer el teléfono

Polycom Realmente es una carpeta que posee a su vez otras carpetasllamadas contacts, logs y overrides

server.cfg Configuración relacionada con servidor de proxy y SIPsip.cfg Todos los parámetros adicionales que se deseen configurar.

Para esto es bueno revisar un manual de Usuario Polycom Segundo, en estos teléfonos no se realiza ninguna conexión a telnet y hasta el momento no se conoce comoreiniciar y enviar los archivos de configuración desde la central Elastix como una acción centralizada. Por ende esnecesario ejecutar lo siguiente desde el propio teléfono Polycom:

Elegir que el tipo de aprovisionamiento es TFTP.Ingresar la IP de la central Elastix.Elegir que lea la configuración por TFTP.Reiniciar el teléfono Polycom.

Estos pasos son iguales en todos los modelos Polycom que Elastix soporta. Así mismo como en el caso de losteléfonos marca ATCOM se genera un historial en la base de datos interna de Elastix acerca de la configuración delteléfono Polycom. Si no hay incidentes entonces ahora el teléfono IP ya está configurado desde la central Elastix y cuando se deseecambiar de extensión sólo debemos ir al módulo Endpoint Configurator, hacer un par de clics y listo.

Actualización por TFTP TFTP es el protocolo usado en este caso para proveer aprovisionamiento. Significa Trivial FTP y es un protocoloque no requiere de ningún tipo de autenticación, es decir que no necesitamos ni un usuario o contraseña pararealizar algún proceso. La mayoría de teléfonos IP soportan este tipo de provisionamiento para poder transferir losarchivos de configuración desde la central Elastix hasta los endpoints y viceversa, como el caso de los teléfonosPolycom que lo usan para descargar la lista de contactos y escribir logs. La central Elastix trae embebido el servicio encargado de escuchar y aceptar transferencias utilizando protocolo TFTP. Es en el archivo de configuración /etc/xinetd.d/tftp donde se personaliza el directorio para uso de tftp. Ennuestro caso es /tftpboot/.

Page 164: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_9/9.3_Endpoint_Configurator.htm[24/11/2011 10:22:39 p.m.]

Personalizando los archivos de configuración Existen ocasiones en que es necesario personalizar ciertos parámetros en los archivos de configuración para losteléfonos IP. Es posible que en versiones superiores a Elastix 2.0 se cuente con una herramienta basada en Webpara realizar estas tareas, pero por ahora el lector podrá hacerlo editando los archivos de plantillas de configuraciónque están en la ruta de la central Elastix /var/www/html/modules/endpoint_configuration/libs/vendors/. En esta ruta vamos a encontrar lo siguiente.

Archivo DescripciónAtcom.cfg.php En este archivo se encuentra la configuración para algunos

modelos ATCOM. Para cambiar alguna configuración serecomienda revisar manuales del archivos de configuraciónpara ATCOM

Polycom.cfg.php En este archivo se encuentra la configuración para algunosmodelos Polycom. Ya que el contenido de los archivos sonXML esto hace que se puedan usar el mismo XML paraalgunos modelos.

Linksys.cfg.php En este archivo se encuentra la configuración para algunosmodelos Linksys. Hay que notar que también tienen formatoXML

Cisco.cfg.php, En este archivo se encuentra la configuración para los modelosde teléfonos Cisco soportados

Aastra.cfg.phpEn este archivo se encuentra la configuración para los modelosde teléfonos Aastra soportados

Grandstream.cfg.php En este archivo se encuentra la configuración para los modelosde teléfonos Grandstream soportados

Snom.cfg.php En este archivo se encuentra la configuración para los modelosde teléfonos Snom soportados

Al hacer cambios en estos archivos plantilla, la próxima vez que use el módulo Endpoint Configuration supersonalización de configuración será reflejada al configurar o actualizar los teléfonos.

Anterior Ir a índice Siguiente

Page 165: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.1_Ruteo_llamadas.htm[24/11/2011 10:22:41 p.m.]

Anterior Ir a índice Siguiente

10Configuración avanzada de PBX

Si espero perderé la audacia de la juventud…-- Alejandro Magno

10.1 Ruteo de llamadas

Rutas Entrantes Esta opción permite configurar el destino de las llamadas que ingresan por una determinada troncal. Cuando unallamada ingresa al servidor, Asterisk puede fijarse en el DID, en el CallerID ó el número de puerto por donde estárecibiéndose dicha llamada en el caso de que se cuente con troncales tipo DAHDI..

Page 166: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.1_Ruteo_llamadas.htm[24/11/2011 10:22:41 p.m.]

Formulario de creación de nueva ruta entrante

Description:Etiqueta que identifica la ruta entrante. DID Number:Para un peer del tipo SIP ó IAX, el DID (Destination-Inward-Dial) es el número destino de la llamada, esasignado por el proveedor y generalmente está asociado al número de cuenta. Por ejemplo si su cuenta es'85679432', ingresando ése número en el campo DID, las llamadas entrantes destinadas a esa cuenta deberíancoincidir con esta información y dirigirse al destino configurado. Si deja este campo en blanco se estará haciendoreferencia a las llamadas entrantes con cualquier número como destino. Caller ID Number:El CID Number es el Caller ID o número telefónico desde donde se origina la llamada que es recibido por Elastix.Este dato no es confiable ya que puede ser fácilmente burlado por hackers. Al dejar este campo en blanco se estaráhaciendo referencia a las llamadas entrantes con cualquier Caller ID. Alert Info:Puede ser usado para activar la característica de rings distintivos soportada en algunos de dispositivos SIP.Requiere de conocimientos particulares de la marca y modelo del dispositivo SIP. Pause Before Answer:

Page 167: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.1_Ruteo_llamadas.htm[24/11/2011 10:22:41 p.m.]

En esta opción se define el número de segundos que deberíamos esperar antes de contestar la llamada entrante. Elprimer propósito para esta opción es permitir que dispositivos conectados en paralelo en esta línea, como lo puedenser máquinas de fax o dispositivos de seguridad electrónica puedan timbrar primero antes de que la central procesela llamada entrante. Privacy Manager:Si se activa esta opción, toda llamada que no llegue con un Caller ID válido no podrá ser enrutada al destino finalde la llamada si antes no se ingresa manualmente el Caller ID, es decir, al llamante se le solicitará que utilizando suteclado del teléfono ingrese el número de origen. Language: Mediante este campo se configura el idioma de los mensajes que serán reproducidos para el tratamiento de lallamada. Escriba “es” para el español. Detect Faxes:Si se habilita esta opción Asterisk tratará de reconocer un tono de fax en la llamada, si reconoce un tono de fax, lallamada será enviada a la extensión por defecto de fax que se configura en “Configuración General”. Set destination:Mediante el “set destination” podemos especificar dónde queremos que la llamada sea terminada, siendo esto: unIVR, una extensión, un miscelaneous destination, colgar la llamada ó a un contexto personalizado.

Rutas Salientes Mediante las rutas salientes podemos indicar por que troncal ó troncales deben ser enviadas las llamadas queoriginan desde alguna extensión interna de la central Elastix.

Formulario de creación de nueva ruta saliente

Route Name:

Page 168: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.1_Ruteo_llamadas.htm[24/11/2011 10:22:41 p.m.]

En este campo se especifica un nombre descriptivo para la troncal para poder facilitar la administración de lasmismas. Route CID:En este campo es posible especificar un número que será utilizado por la llamada como número de origen. Estacaracterística de cambiar el número origen a discreción del administrador de la central debe estar soportada por elproveedor de las troncales utilizadas para realizar la llamada. Route Password:Si llenamos este campo, cada vez que una llamada intente utilizar esta troncal, al llamador le será solicitada queingrese ese mismo patrón como clave. Si la clave es ingresada correctamente la llamada es conectada, casocontrario la llamada es descartada. Solo es permitido el ingreso de dígitos. Emergency Dialling:Con esta opción podemos especificar que la ruta es para llamadas de emergencia. Se puede especificar un diferenteCaller ID. Dial Patterns:El patrón de marcado es el conjunto ó patrón de dígitos que Asterisk usa para discriminar si el número marcado porla extensión interna “hace juego” con el patrón configurado en la ruta saliente y de este modo determinar el canalpor donde debe enviar la llamada. Existen reglas de cómo especificar los patrones de marcados, las cuales indicamos a continuación: Patrón DescripciónX Representa cualquier dígito de 0-9Z Representa cualquier dígito de 1-9N Representa cualquier dígito de 2-9[1237-9] Representa cualquier dígito entre corchetes. Representa uno o más caracteres| Separa el número ubicado a la izquierda del número

marcado. Por ejemplo: 9|NXXXXXX deberíarepresentar los números marcados como “92234567”pero sólo debería pasar “2234567”

Trunk Sequence:Se lista e indica el orden en que se debe intentar el uso de las troncales. Cuando un número digitado por unllamador “hace juego” con el patrón de marcado especificado, Asterisk intentará realizar la llamada por lastroncales especificadas en esta opción en el orden en que son listadas.

Anterior Ir a índice Siguiente

Page 169: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.2_Troncales.htm[24/11/2011 10:22:43 p.m.]

Anterior Ir a índice Siguiente

10.2 Troncales Una troncal es aquella que permite terminar una llamada a otro sistema externo de comunicación VoIP. Alguno delos tipos de troncales son:

DAHDIIAX2SIPENUMDUNDiCustom

Veamos algunos de los parámetros a configurar en una troncal DAHDI.

Creación de nueva troncal tipo DAHDI

Trunk Description:Con este campo se le asigna un nombre distintivo a la troncal. Outbound Caller ID:En esta opción es posible especificar el número de origen o Caller ID que la llamada usará cuando use esa troncal.Es necesario que el proveedor de la línea telefónica conectada a ese puerto DAHDI permita el cambio de CallerID.El formato utilizado es: “Nombre del llamador” <###########>

Page 170: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.2_Troncales.htm[24/11/2011 10:22:43 p.m.]

Si no se quiere usar un caller ID dejar en blanco esta opción Maximum channels:Esta opción limita el número de canales que pueden ser usados en una troncal. Al decir canales se refiere alnúmero de llamadas simultáneas que se pueden hacer, tanto entrantes como salientes. Dial Rules:Las reglas de marcado indican cómo Asterisk debería marcar para hacer la llamada en una troncal. Esta opciónpuede ser usada para adicionar ó remover prefijos. Si un número marcado no “hace juego” con los patronescolocados en estas reglas, es marcado como fue digitado. Las reglas pueden ser especificadas mediante la siguiente sintaxis: Patrón DescripciónX Representa cualquier dígito de 0-9Z Representa cualquier dígito de 1-9N Representa cualquier dígito de 2-9[1237-9] Representa cualquier dígito entre corchetes. Representa uno o más caracteres| Separa el número ubicado a la izquierda del número

marcado. Por ejemplo: 9|NXXXXXX deberíarepresentar los números marcados como “92234567”pero sólo debería pasar “2234567”

+ Adiciona un prefijo al número marcado. Por ejemplo:001+NXXNXXXXXX debería agregar el 001 alnúmero 3058293438 cuando este es marcado

Troncales de tipo IAX y SIP Además de las configuraciones arriba mostradas, se deben especificar configuraciones entrantes y salientes quegeneralmente son provistas por el proveedor de servicios de voz. Las configuraciones pueden incluir username,password, codec utilizado, el host con el cual debe de registrarse, etc. Ejemplo de configuración de los detalles del Peer: allow=ulaw&alaw&gsm&ilbc&g726&adpcm&lpc10canreinvite=nodisallow=alldtmfmode=infofromuser=myusernamehost=nyc.voicepulse.comqualify=5000secret=mypasswordsendrpid=yestype=peerusername=myusername

Page 171: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.2_Troncales.htm[24/11/2011 10:22:43 p.m.]

Además es posible que se requiera una cadena de registro que tiene la siguiente sintaxis: myusername:mypassword@host

Troncales de tipo DAHDI Las troncales de tipo DAHDI son las asociadas a hardware de telefonía instalado en la máquina y usa el módulochan_dahdi.so. Los archivos asociados a este tipo de troncales son el /etc/asterisk/chan_dahdi.conf y los archivosbajo la carpeta /etc/dahdi/ Las troncales DAHDI son creadas mediante un número asociado a la posición del canal en el hardware.

Troncales personalizadas. Estas troncales son creadas cuando se usan protocolos no muy comunes en Asterisk como H323, CAPI, etc. Se debe especificar un string de marcado. Por ejemplo: CAPI/XXXXXXX

Anterior Ir a índice Siguiente

Page 172: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.3_Tarifacion.htm[24/11/2011 10:22:46 p.m.]

Anterior Ir a índice Siguiente

10.3 Tarifación La utilidad “Rates” del Menú “Billing” dentro de la pestaña de “Reports” del Elastix nos permite visualizar yconfigurar las tarifas que se usarán para la facturación de llamadas.

Listado de tarifas definidas

Visualizar, Editar y Eliminar El enlace Ver nos llevará a una pantalla donde se mostrará los datos de la tarifa. Para eliminar una tarifa, de clic en el botón Eliminar. Puede además modificar los valores de la tarifa dando clic en el botón Editar. Los únicos valores que puedecambiar son: Nombre, Tarifa y Tarifa de Conexión.

Formulario de edición de tarifa

Crear Tarifa Para agregar una nueva tarifa dar clic en el botón Crear Nueva Tarifa. Se mostrará un formulario en el que seingresarán los siguientes campos:

Prefijo: Prefijo telefónico al cual se aplicará la tarifaNombre: Nombre para la tarifaTarifa: Valor de la tarifaTarifa de Conexión: Valor de conexiónTroncal: Troncal de la cual se tomará las contabilización de las llamadas.

Page 173: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.3_Tarifacion.htm[24/11/2011 10:22:46 p.m.]

Creación de nueva tarifa

Reporte de Facturación La opción “Billing Report” del Menú “Billing” del Elastix nos permite visualizar el detalle de las llamadas con surespectivo costo y tarifa aplicada. El reporte cambiará dependiendo de los valores de filtrado:

Fecha Inicio: Fecha a partir de la cual se seleccionarán las llamadas.Fecha Fin: Fecha hasta la cual se seleccionarán las llamadas.Campo: Campos adicionales de filtrado: Fuente, Destino, Canal Destino.

Reporte de tarifación

Distribución de Destinos La opción “Destination Distribution” del Menú “Billing” del Elastix nos permite visualizar mediante un gráfico ladistribución de las llamadas salientes agrupadas por tarifa. El gráfico cambiará dependiendo de los valores defiltrado:

Page 174: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.3_Tarifacion.htm[24/11/2011 10:22:46 p.m.]

Fecha Inicio: Fecha a partir de la cual se seleccionarán las llamadasFecha Fin: Fecha hasta la cual se seleccionarán las llamadasCriterio de distribución: Distribución por Tiempo, Distribución por Número de Llamadas, Distribución porCosto

Distribución por Tiempo La opción de distribución por tiempo muestra un gráfico de pastel del tiempo traficado para cada troncal. Ademásmuestra una lista de las troncales que más tiempo han traficado.

Gráfico de pastel que muestra la distribución de destinos en base a tiempo de uso

Distribución por Número de Llamadas Muestra un gráfico de pastel del número de llamadas para cada troncal. Además muestra una lista de las troncalescon más número de llamadas traficadas.

Distribución de destinos en base a número de llamadas

Distribución por Costo Muestra un gráfico de pastel dividido por el costo resumido por troncal. Es decir que para cada troncal se computael costo de todas las llamadas traficadas. Este cálculo de costo está basado en las tarifas ingresadas en el menú“Tarifas” (rates).

Page 175: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.3_Tarifacion.htm[24/11/2011 10:22:46 p.m.]

Configurar Facturación Dentro de esta opción tenemos dos secciones que explicaremos a continuación.

Configuración de Tarifa por Omisión La opción “Configuración de Tarifa por Omisión” del Menú “Billing” del Elastix nos permite determinar el costopor minuto y de conexión para la ruta por omisión o dicho de otra manera la tarifa que se aplicará cuando no seencuentre otra tarifa que aplicar a una llamada.

Tarifa por omisión

Configuración de Troncales para Facturación La opción “Configuración de Troncales” del Menú “Billing” del Elastix nos permite determinar cuáles serán lastroncales que se usarán para obtener las llamadas para el proceso de facturación. El listado muestra todas las troncales registradas, deberá seleccionar las que se usarán para la facturación y luegodar click en el botón “Habilitar para Facturar”.

Troncales habilitadas para tarifación seleccionadas con visto

Anterior Ir a índice Siguiente

Page 176: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.4_Reportes.htm[24/11/2011 10:22:47 p.m.]

Anterior Ir a índice Siguiente

10.4 Reportes

Reporte CDR CDR es la abreviación de Call Detail Record o Registro de Detalle de Llamada. La opción “Reporte CDR” en la pestana de “Reportes” del Elastix nos permite visualizar un listado con el detallede las llamadas.

Reporte de CDRs

El reporte cambiará dependiendo de los valores de filtrado:

Fecha Inicio: Fecha a partir de la cual se seleccionarán las llamadasFecha Fin: Fecha hasta la cual se seleccionarán las llamadasCampos adicionales de filtrado: Fuente, Destino, Canal DestinoEstado de la llamada: ANSWERED, BUSY, FAILED, NO ANSWER

Nota: Este reporte es exportable a formato CSV (separado por comas). Este formato se puede abrir desde unahoja de cálculo para realizar las manipulaciones matemáticas que se estime conveniente como por ejemplosacar promedios de tiempo de llamada por extensión.

Uso de Canales La opción “Uso de Canales” del Menú “Reportes” del Elastix nos permite visualizar gráficamente el número dellamadas simultáneas para cada canal.

Page 177: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.4_Reportes.htm[24/11/2011 10:22:47 p.m.]

Reporte de uso de canales

Anterior Ir a índice Siguiente

Page 178: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.5_Configuracion_DISA.htm[24/11/2011 10:22:49 p.m.]

Anterior Ir a índice Siguiente

10.5 Configuración DISA El módulo DISA (Direct Inward System Access) permite que los usuarios puedan acceder telefónicamente a losservicios provistos por la central Elastix desde el exterior, el acceso se realiza obteniendo un tono "interno" demarcado.. Con este tono "interno" puedo tener acceso a las mismas facilidades que desde dentro. Por ejemplo,podría realizar llamadas internacionales (si es permitido). Normalmente el soporte DISA no está disponible para todos los empleados de una compañía y es necesaria unaclave para poder obtener el tono "interno". Para poder ingresar la clave algunas compañías proveen de una opciónoculta en el IVR principal de la compañía. En todo caso hay que tomar las precauciones para que el acceso DISAno pueda ser quebrantado por usuarios indeseados, quienes podrían aprovecharlo para hacer llamadas a costa de lacompañía. Para configurar un acceso DISA debemos ir al menú "PBX -> PBX Configuration -> DISA" y obtendremos unapantalla como la siguiente.

Formulario para crear un nuevo acceso DISA

Nombre de DISA: Nombre distintivo del acceso DISA. PIN: La clave para que el usuario acceda al soporteDISA (tono interno)Tiempo de espera para la respuesta: Tiempo máximo que la aplicación DISA espera para que el usuariocomplete el PINTiempo de espera de marcado: Máximo tiempo entre dígitos.Pedir Confirmación: Solicita confirmación antes de solicitar la contraseña.Identificador de llamante: Si es utilizado este campo, todas las llamadas salientes originadas desde estaDISA utilizarán este número como CallerID.Contexto: Contexto que utilizarán las llamadas de la DISA.

Page 179: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.5_Configuracion_DISA.htm[24/11/2011 10:22:49 p.m.]

Permite Colgar: Si se habilita esta opción, el usuario que realiza una llamada por esa DISA tiene laposibilidad de colgar la llamada presionando “**” para obtener un nuevo tono de marcado y poder realizaruna nueva llamada.

Luego, para que éste acceso DISA esté disponible desde el IVR principal debemos modificar dicho IVR y asociaruna opción con el acceso DISA recientemente creado.

Anterior Ir a índice Siguiente

Page 180: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.6_Condiciones_de_tiempo.htm[24/11/2011 10:22:50 p.m.]

Anterior Ir a índice Siguiente

10.6 Condiciones de tiempo El uso de condiciones de tiempo es una característica muy útil para muchos negocios que quieren modificar elcomportamiento de su PBX dependiendo de la hora del día, día de la semana e inclusive el día del año. Porejemplo, la compañía X desea que en la noche las llamadas a ventas no vayan a la cola de ventas sino que sereproduzca un mensaje indicando el horario de atención y diciendo también que pueden contactar a un númeroalternativo para casos urgentes; o también la compañía Z que quiere reproducir un IVR de bienvenida distinto alhabitual durante los fines de semana ya que tienen promociones de fin de semana. Las condiciones de tiempo son funcionalidad provista gracias a la integración de Elastix con el software FreePBX.Para configurar una condición de tiempo, es necesario saber que se debe implementar ingresando a dos menús. Elprimer menú llamado “Grupo Horario” se utiliza para definir los distintos horarios que se necesitarán paradiscriminar las condiciones de tiempo, y luego el menú “Condiciones de Tiempo” que será utilizada paradeterminar el destino de la llamada de acuerdo al grupo horario anteriormente definido. Para ingresar a la utilidad de “Grupo Horario”, debe dirigirse a la pestaña de “PBX -> PBX Configuration ->Grupo Horario”. Aquí accederemos a un formulario que nos permitirá establecer el rango de tiempo que seráutilizado luego en el menú de “Condiciones de Tiempo”..

Añadiendo un nuevo grupo horario

Luego de definir el “Grupo Horario” es necesario ingresar a la utilidad de “Condiciones de Tiempo” para relacionareste grupo horario con una entidad como por ejemplo un IVR, una extensión, una cola, un voicemail, etc.

Page 181: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_10/10.6_Condiciones_de_tiempo.htm[24/11/2011 10:22:50 p.m.]

Añadiendo una nueva condición de tiempo

Una vez configurada, no olvide seleccionarla dentro de sus rutas entrantes.

Anterior Ir a índice Siguiente

Page 182: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.1_Fundamentos_FreePBX.htm[24/11/2011 10:22:52 p.m.]

Anterior Ir a índice Siguiente

11Funcionamiento interno de FreePBX

La libertad no se implora, se conquista-- Eloy Alfaro

11.1 Fundamentos de FreePBX FreePBX es un software de configuración de Asterisk que ha sido integrado como parte de la distro Elastix.Básicamente este software se encarga de generar los archivos de configuración requeridos por Asterisk a partir dela configuración ingresada por el usuario desde la interfaz Web. Para realizar esta tarea FreePBX la divide en dos pasos:

1. Recaba la configuración deseada por el usuario en una base de datos de configuración. En el caso de Elastixse usa el motor de base de datos MySQL.

2. Convierte la información almacenada en MySQL en archivos de configuración vía la herramienta

retrieve_conf Para ilustrar este proceso veamos la siguiente figura.

Page 183: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.1_Fundamentos_FreePBX.htm[24/11/2011 10:22:52 p.m.]

Funcionamiento y componentes de FreePBX

Anterior Ir a índice Siguiente

Page 184: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.2_Organizacion_de_archivos.htm[24/11/2011 10:22:52 p.m.]

Anterior Ir a índice Siguiente

11.2 Organización de archivos FreePBX lee y escribe información en algunos directorios para su correcto funcionamiento. A continuación seencuentra una lista de los más importantes. Directorio Descripción/var/www/html/admin/ Lugar donde reside el GUI de FreePBX/etc/asterisk/ Archivos de configuración de Asterisk

modificados por FreePBX/var/lib/asterisk/agi-bin/ Lugar donde residen los scripts AGI de

Asterisk. FreePBX cuenta con algunosscripts en esta carpeta como eldialparties.agi

/var/lib/asterisk/bin/ Algunos binarios o vínculos simbólicoscorrespondientes que son utilizados porFreePBX.

/usr/local/sbin/ El script amportal se encuentra aquí ya quesolo puede ser manipulado por root

/var/lib/asterisk/sounds/ Sonidos que se utilizan en el plan demarcado por FreePBX

/var/lib/asterisk/sounds/custom/ Sonidos que han sido creados por elusuario. Por ejemplo cuando se crea un IVRde bienvenida

/var/spool/asterisk/voicemail/ Lugar donde se almacenan los voicemails/var/spool/asterisk/monitor/ Lugar donde se almacenan las grabaciones

de voz/var/log/asterisk/cdr-csv/ Lugar donde se escriben los CDRs en

formato texto

Anterior Ir a índice Siguiente

Page 185: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.3_Configuracion.htm[24/11/2011 10:22:53 p.m.]

Anterior Ir a índice Siguiente

11.3 Configuración

amportal.conf El archivo /etc/amportal.conf es un archivo de texto plano que contiene información general deconfiguración y es leído por FreePBX. Es decir, este es el principal archivo de configuración de FreePBX y puedeser editado manualmente en caso de requerirse. En este archivo de configuración se encuentra la información de acceso a la base de datos (usuario y contraseña) aligual que el tipo de autenticación que FreePBX usará para con sus usuarios Web. Este archivo está biendocumentado por lo que no entraremos en detalles sobre las opciones o directivas de configuración.

Anterior Ir a índice Siguiente

Page 186: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.4_retrieve_conf.htm[24/11/2011 10:22:54 p.m.]

Anterior Ir a índice Siguiente

11.4 retrieve_conf: Generador del plan de marcado retrieve_conf es un programa escrito en PHP que se encarga de generar el plan de marcado a partir de lainformación almacenada en la base de datos (MySQL en nuestro caso). Este programa usualmente se ejecuta desdeel Web a través de un script PHP cada vez que damos clic en la barrita roja de FreePBX que dice ApplyConfiguration Changes Here. Sin embargo, retrieve_conf puede ser invocado inclusive desde la línea decomandos.

Anterior Ir a índice Siguiente

Page 187: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.5_dialparties.agi.htm[24/11/2011 10:22:54 p.m.]

Anterior Ir a índice Siguiente

11.5 dialparties.agi Este es un script AGI escrito en PHP que se invoca desde el plan de marcado cuando se quiere hacer una llamada.Su principal tarea es la de revisar el estado de la extensión a la que se está llamando, así como también ciertasopciones que pudieran estar configuradas en dicha extensión (call waiting, call forward, do not disturb).Finalmente, el script retorna dicha información para que se pueda tomar una acción acorde como por ejemplodevolver al llamante un tono de ocupado en el caso de DND o rutear la llamada a otra extensión en el caso de callforward. Si la extensión está disponible y no se encuentran opciones activadas la llamada transcurre sininconvenientes. Para realizar su trabajo dialparties.agi consulta la base de datos de Asterisk (en el archivo/var/lib/asterisk/astdb). A continuación algunas líneas de diagnóstico que aparecen en el CLI cuando se intenta hacer una llamada. Estaslíneas son devueltas por el script dialparties.agi. dialparties.agi: Caller ID name is 'Pedro Paramo' number is '5454'dialparties.agi: Methodology of ring is 'none' -- dialparties.agi: Added extension 1616 to extension map -- dialparties.agi: Extension 1616 cf is disabled -- dialparties.agi: Extension 1616 do not disturb is disableddialparties.agi: Extension 1616 has ExtensionState: 0 -- dialparties.agi: Checking CW and CFB status for extension 1616 -- dialparties.agi: dbset CALLTRACE/1616 to 5454 -- dialparties.agi: Filtered ARG3: 1616

Nota: Este script puede ser sobrescrito por el propio FreePBX por uno nuevo por lo que si se realizancambios en su código se debe tener este hecho en cuenta. dialparties.agi está ubicado en la ruta/var/lib/asterisk/agi-bin/dialparties.agi.

Anterior Ir a índice Siguiente

Page 188: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_11/11.6_Estructura_modulo_ FreePBX.htm[24/11/2011 10:22:55 p.m.]

Anterior Ir a índice Siguiente

11.6 Estructura de un módulo de FreePBX Esta sección tiene como propósito el que podamos entender mejor el funcionamiento de FreePBX con miras asolucionar posibles problemas. Los módulos de FreePBX tienen la siguiente estructura mínima de archivos. Nombre del archivo Descripciónmodule.xml Contiene información del módulo en

formato XMLpage.<módulo>.php Archivo principal del módulo conteniendo

la funcionalidad necesaria. Como es deimaginar, la palabra <módulo> debe serreemplazada por el respectivo nombre delmódulo.

functions.inc.php Librería de funciones PHP tanto para usodel módulo como para que puedan sercompartidas por otros componentes deFreePBX

install.sql Contiene sentencias SQL que se ejecutaránsobre la base de datos al instalar el módulo.Básicamente para crear las tablas necesariaspara el módulo

uninstall.sql Contiene las sentencias SQL necesarias paradesinstalar el módulo. Básicamente pararemover las tablas creadas

install.php Script PHP para ser ejecutado al momentode instalación del módulo

uninstall.php Script PHP para ser ejecutado al momentode desinstalación del módulo

Anterior Ir a índice Siguiente

Page 189: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_12/12.1_Interconexion_servidores_Elastix.htm[24/11/2011 10:22:56 p.m.]

Anterior Ir a índice Siguiente

12Conectando Servidores Elastix

Cualquier poder, si no se basa en la unión, es débil-- Jean de la Fontaine

12.1 Interconexión entre dos servidores Elastix Una de las ventajas de usar Elastix es que fácilmente podemos interconectar dos servidores Elastix de tal maneraque lugares remotos se puedan comunicar con un solo plan de marcado. A continuación veremos cómo interconectar dos servidores Elastix mediante una troncal de tipo SIP. Supongamos que queremos interconectar un servidor Elastix localizado en un punto A con otro servidor Elastix enun punto B. El resultado debe ser que un teléfono conectado al servidor Elastix en el punto A pueda comunicarsemarcando simplemente la extensión del teléfono conectado al servidor Elastix en el punto B, y viceversa.

Page 190: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_12/12.1_Interconexion_servidores_Elastix.htm[24/11/2011 10:22:56 p.m.]

Interconectando dos Elastix

Para implementar esto se requiere definir dos cosas:

1. La troncal SIP entre los servidores Elastix2. Las rutas salientes en cada servidor Elastix

Toda la configuración se puede realizar desde la interfaz Web de Elastix desde el menú PBX -> PBX Configuration

Definiendo la troncal SIP Definimos el nombre de la troncal, el cual en nuestro caso servirá de username para el proceso de registro.Debemos crear la troncal del Elastix en el punto A como pointA y la del punto B como pointB. Ver capítulo 10 paradetalles sobre la creación de troncales SIP. Luego definimos los detalles del peer que en este caso serán los siguientes: host=dynamicsecret=welcometrunk=yestype=friend

Esta configuración de la sección de peer se debe repetir en ambos servidores Elastix. En este ejemplo hemosdefinido como la palabra welcome como secret. Ahora debemos definir el register string (cadena de registro) usando pointA o pointB como username según sea elcaso. Para el servidor Elastix en el punto A debemos tener: pointB:[email protected]

Para el servidor Elastix en el punto B debería ser:

Page 191: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_12/12.1_Interconexion_servidores_Elastix.htm[24/11/2011 10:22:56 p.m.]

pointA:[email protected]

Una vez establecida esta configuración en ambos Elastix podemos verificar desde el Asterisk CLI si las troncalesSIP se encuentran registradas. Al ejecutar el comando sip show registry en el servidor Elastix del punto Adeberíamos ver algo como lo que sigue: elastix*CLI> sip show registryHost Username Refresh State Reg.Time192.168.1.240:5060 pointB 105 Registered Fri,11 Apr 2008 10:29:43

El siguiente paso es definir los detalles del user en la misma pantalla de creación de troncales SIP anterior. Lasección de user establece donde se quiere terminar la llamada. En este caso queremos que sea accesible aextensiones locales, así que bastará con colocar el contexto primario from-internal. Esto indica que cuando lallamada entre por la troncal se iniciará en el contexto aquí especificado. La configuración es como sigue: context=from-internalhost=192.168.1.240insecure=verytype=friend

Definiendo las rutas salientes Ver capítulo 10 para detalles sobre la creación de rutas salientes.

Primero determinamos el nombre de la ruta saliente. En este caso, especificaremos la ruta saliente en elservidor del punto A como: ElastixB

Luego definimos el patrón de marcado. En este caso usaremos el siguiente patrón de marcado: 2|XXX.Estamos asumiendo que para marcar a las extensiones conectadas al servidor Elastix en el punto B se debemarcar con el número 2 adelante.

Finalmente escogemos la troncal por la cual debe irse la llamada. En este caso escogemos la troncalSIP/pointA

Anterior Ir a índice Siguiente

Page 192: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_12/12.2_Conexion_proveedores_de_llamadas_via_IP.htm[24/11/2011 10:22:57 p.m.]

Anterior Ir a índice Siguiente

12.2 Conexión con proveedores de llamadas vía IP La popularidad de los proveedores de servicios de voz (Voice Service Providers o VSP) ha crecido increíblementeen los últimos años. Estas compañías proveen conexiones SIP o IAX para llamadas locales o internacionales porInternet a bajo costo. En esta sección estableceremos una conexión SIP con un proveedor que nos permitirá hacer llamadas dentro de losEstados Unidos. Nuestra meta es registrar nuestra troncal de tipo SIP con un VSP que nos permita realizar llamadas a USA desdecualquier teléfono IP conectado a nuestro servidor Elastix. Para implementar esto se requiere definir dos cosas:

1. La troncal SIP del servidor Elastix2. La ruta saliente en el servidor Elastix

Definiendo la troncal SIP Como vimos anteriormente, lo primero que se debe hacer es definir el nombre de la troncal. En este caso lellamaremos: VP-SIP-NYC. Ver capítulo 10 para detalles sobre la creación de troncales SIP. Ahora debemos definir las características del peer. Esta información debe ser proporcionada por el VSP.Generalmente, los VSP entregan esta misma información para todos sus usuarios con la única diferencia delusername y el password. Como ejemplo, nuestro VSP nos pidió que configuremos la troncal SIP de la siguiente forma. allow=ulaw&alaw&gsm&ilbc&g726&adpcm&lpc10canreinvite=nodisallow=alldtmfmode=infofromuser=myusernamehost=nyc.voicepulse.comqualify=5000secret=mypasswordsendrpid=yestype=peerusername=myusername

Luego agregamos la cadena de registro que en nuestro caso sería la siguiente. myusername:[email protected]

Page 193: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_12/12.2_Conexion_proveedores_de_llamadas_via_IP.htm[24/11/2011 10:22:57 p.m.]

Definiendo la ruta saliente Ver capítulo 10 para detalles sobre la creación de rutas salientes.

Primero determinamos el nombre de la ruta saliente. En este caso la nombraremos: INTERNACIONAL

Luego definimos el patrón de marcado. En este caso usaremos el siguiente patrón de marcado: 00. Estamosasumiendo que para marcar un número al exterior se requiere anteponer los dos ceros.

Finalmente escogemos la troncal por la cual debe irse la llamada. En este caso escogemos la troncal SIP/VP-SIP-NYC

Una vez establecida esta configuración podemos verificar desde el Asterisk CLI si la troncal SIP se encuentraregistrada. Al ejecutar el comando sip show registry en el servidor Elastix deberíamos ver algo como loque sigue: elastix*CLI> sip show registryHost Username Refresh State Reg.Timenyc.voicepulse.com:5060 myusername 105 Registered Fri,11 Apr 2008 10:29:43

Al marcar un número internacional como 0018773527849 la llamada debe establecerse por medio de este VSP.

Anterior Ir a índice Siguiente

Page 194: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/...los/capitulo_12/12.3_Conexion_predefinida_con_proveedores_de_llamadas_via_IP.htm[24/11/2011 10:22:59 p.m.]

Anterior Ir a índice Siguiente

12.3 Conexión predefinida con proveedores de llamadas víaIP Existe otra forma de crear troncales SIP para interconectar el servidor Elastix con un VSP. La interfaz de VoIPProvider nos permite ingresar los parámetros de peer y cadena de registro directamente en un formulario. Además,podemos seleccionar entre los proveedores más comunes los cuales ya cuentan con parámetros predeterminados deconfiguración. La siguiente imagen muestra la configuración de una troncal SIP con un VSP predefinido.

Interfaz Web para configurar VSPs

Anterior Ir a índice Siguiente

Page 195: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.1_Sintomas_problemas_de_voz.htm[24/11/2011 10:22:59 p.m.]

Anterior Ir a índice Siguiente

13Calidad de voz

Calidad es hacer las cosas bien cuando nadie está controlando-- Henry Ford

13.1 Síntomas de los problemas de voz Enumerar los problemas que afectan la calidad de voz es difícil pues influye mucho la percepción de la persona.Las causas del deterioro de la calidad de voz son variadas y difícil de categorizar. En esta sección revisaremos losmás comunes explicando sus causas y posibles soluciones.

Eco El eco es uno de los síntomas más comunes y es muy fácil reconocerlo. Se produce cuando una parte de la señal deida se refleja en la señal de vuelta. El eco consiste en la repetición una o más veces la conversación con ciertodesfase de tiempo. Hay algunas causas del eco pero una de las más comunes se produce en las líneas analógicas cuando se combinanlas señales en el convertidor híbrido o convertidor de 2 4 hilos (Ver capitulo 1 para más detalles). Esto sucedeporque es muy difícil separar las señales de ida y de vuelta de manera eficaz. El problema se agrava cuando la impedancia de la línea telefónica varía mucho. Muchas de las tarjetas telefónicasdisponibles para Asterisk no disponen de un buen mecanismo para el ajuste dinámico de la impedancia de la líneacon la impedancia de la tarjeta. Por esta razón una parte de la onda se refleja causando eco.

Nota: hay que recordar que para que un receptor absorba eficientemente la potencia de la señal recibida,

Page 196: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.1_Sintomas_problemas_de_voz.htm[24/11/2011 10:22:59 p.m.]

su impedancia debe coincidir con la de la línea. Sin embargo, existe una forma de acoplar estas impedancias lo mejor posible. Esto se puede realizar con programallamado fxotune disponible en Elastix desde la línea de comandos. Lamentablemente esta utilería se debeejecutar manualmente y con el servicio Asterisk apagado. Para líneas con problemas de eco se recomiendaejecutarlo en horas no laborables una vez por semana debido a que puede llevarse un tiempo considerable. Elcomando es el siguiente. fxotune -i 5

El comando fxotune prueba enviando una señal pura por la línea y escuchando el retorno. Esto lo hace muchasveces por cada línea hasta encontrar el mejor valor de ganancia. Al final, este software escribe el valor de laganancia en el archivo /etc/fxotune.conf Al finalizar su ejecución se debe instruir a DAHDI que cargue los valores nuevos de ganancia. Esto lo podemoshacer con el siguiente comando: fxotune -s

Esto lo debemos ejecutar siempre antes de arrancar Asterisk por lo que se recomienda incluirlo al final del scriptde arranque de DAHDI ubicado en la ruta /etc/init.d/dahdi para no tener que hacerlo manualmente cadavez.

Nota: Es muy importante hacer notar que si se utiliza fxotune para tratar de acoplar las líneas no se debenconfigurar las variables txgain o rxgain en el chan_dahdi.conf ya que sobrescribirán el trabajo del fxotune.

Ahora solo resta encender Asterisk nuevamente. Finalmente, otra causa del eco es de naturaleza acústica provocado cuando la señal de sonido se retroalimentadesde el micrófono al audífono. Esto es más notable cuando hablamos por altavoz. Por supuesto el diseño delteléfono hace mucha diferencia y hay modelos que introducen menos eco acústico que otros.

Bajo nivel de volumen Muchas redes telefónicas de baja calidad atenúan la señal de manera significativa haciendo que escuchemos unvolumen muy bajo. Esto obviamente afecta la calidad de voz, haciendo que la conversación muchas veces seainentendible o haciendo que no se puedan detectar los tonos de DTMFs. Tanto el volumen de recepción como el de transmisión pueden ser amplificados mediante parámetros en el archivochan_dahdi.conf. Sin embargo se debe tener mucho cuidado pues en ocasiones un volumen bajo significa unalínea mal acoplada y por ende la mejor solución es utilizar la utilería fxotune para corregir el problema. Simodificamos los parámetros de ganancia arbitrariamente podríamos conseguir empeorar el eco en la línea. El parámetro que modifica la ganancia de la señal de transmisión se llama txgain y el de recepción se llamarxgain. Ambos se pueden editar en el archivo chan_dahdi.conf.

Page 197: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.1_Sintomas_problemas_de_voz.htm[24/11/2011 10:22:59 p.m.]

Retardo de voz El retardo de voz no es otra cosa que la demora que experimenta la voz en llegar a su destino. Usualmente elretardo es menor a un segundo y si es menor a 200 ms pasa desapercibido. Cuando el retardo es mayor a 500 ms los interlocutores tienden a interrumpirse y la conversación se traslape. Estoes irritante para la comunicación.. Es casi imposible eliminar el retardo a nivel del servidor pues en la gran mayoría de los casos este es un síntoma deproblemas inherentes en la red de comunicaciones. Es decir que si se quiere eliminarlo habrá que analizar posiblescambios en la red de comunicaciones.

Distorsión de voz En esta categoría recaen diferentes problemas. El más común de ellos es el de la voz robotizada. Cuando se utiliza un codec para optimizar el uso de ancho de banda (Ej: gsm) y la conectividad experimentaproblemas entonces la perdida de información causa la distorsión.En estos casos es recomendable cambiar de codec a uno que ofrezca menor compresión de voz.

Comunicación entrecortada Este problema tan molestoso normalmente está relacionado con la pérdida de paquetes en la red. Las causasprincipales de la pérdida de paquetes son una latencia elevada o un ancho de banda limitado, entre otros. Lacomunicación entrecortada también puede ser ocasionada por un jitter elevado. Estudiaremos más sobre el jitter enla siguiente sección. En todo caso lo normal es buscar la causa de este problema primero en la red y luego en el servidor. El entrecortede la voz puede ser producto de problemas con el servidor cuando el consumo de los recursos como memoria yCPU se encuentran muy elevados. Por lo general si la latencia máxima (absoluta, no promedio) de la red es 150 ms y el canal de comunicaciones nose encuentra saturado podemos estar tranquilos de que los problemas de comunicación entrecortada no nos quitaránel sueño.

Anterior Ir a índice Siguiente

Page 198: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/...lo_13/13.2_Parametros_relacionados_con_calidad_de_voz_en_redes_de_paquetes.htm[24/11/2011 10:23:00 p.m.]

Anterior Ir a índice Siguiente

13.2 Parámetros relacionados con la calidad de voz en redesde paquetes

Retardo de red Hay que distinguir aquí que no estamos hablando del retardo de voz sino del retardo de los paquetes en la red. Una manera sencilla de calcular (aproximadamente) el retardo de la red es utilizando el comando ping. Estecomando envía paquetes de prueba a un destino y nos presenta un pequeño resumen estadístico de los paquetesenviados. El resumen luce como el siguiente. --- ping statistics ---6 packets transmitted, 6 received, 0% packet loss, time 5004msrtt min/avg/max/mdev = 73.055/74.181/74.852/0.710 ms

Aquí podemos ver algunos parámetros como el retardo mínimo, promedio, máximo y su desviación.

Pérdida de paquetes En algunas ocasiones ciertos de los paquetes que componen un mensaje no llegan a su destino. Pueden existir muchas razones para que suceda esto como equipos defectuosos o saturados, pérdidas en el medio de transmisión(cables mal terminados, ruido eléctrico elevado), entre otros. En el resumen del comando ping en la sección de retardo de red vemos que también se nos reportaporcentualmente las pérdidas de paquetes. Lo deseable es que no existan pérdidas de paquetes en lo absoluto (0%).Si existen, hay que investigar el por qué. Inclusive pérdidas de menos del 1% pueden afectar a las conversaciones de voz sobre IP. Este problema es aúnmayor cuando usamos codecs de gran compresión.

Jitter El jitter es un parámetro muy importante cuando se habla de calidad de voz en redes de paquetes. El jitter sedefine como la variabilidad del retardo de red y normalmente está en el orden de los milisegundos. Este parámetro es necesario para analizar la calidad de voz ya que tener un promedio de retardo de red bajo no essuficiente para garantizar una buena calidad.Cuando existe un promedio de retardo de red aceptable pero muy variable existe mayor probabilidad de que lospaquetes lleguen en desorden a su destino o con retardos excesivos. Debido a que la comunicación de voz es entiempo real no se puede esperar a que lleguen todos los paquetes y habrá que descartar los que se demoren más delo necesario. Por tanto, si tenemos un jitter elevado es más probable que se descarten paquetes y por lo tantooigamos una conversación entrecortada.

Page 199: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/...lo_13/13.2_Parametros_relacionados_con_calidad_de_voz_en_redes_de_paquetes.htm[24/11/2011 10:23:00 p.m.]

Nota: Muchas personas confían ciegamente en el comando ping para obtener el retardo de una red eincluso para calcular el jitter haciendo cálculos manuales. Pese a que ping puede usarse en situaciones deapremio, el comando ping no envía paquetes de voz sino tráfico ICMP el cual no recibe el mismotratamiento en la red. Inclusive en ciertas redes este protocolo puede tener una limitación de ancho debanda totalmente diferente al de los paquetes de voz. La manera más exacta de calcular el jitter es conpaquetes RTP reales y esto se puede analizar con un sniffer.

Jitter buffers Para minimizar los efectos negativos del jitter algunos fabricantes de soluciones de VoIP han pensado en esperarpor paquetes de voz extraviados antes de volver a ensamblar la señal de voz en el destino. A medida que estospaquetes lleguen serán reordenados para reconstruir el mensaje original. Esta solución no está libre de problemas ya que con esta acción estamos también aumentando el retardo de red alhacer que el mensaje llegue a su destino después del reordenamiento. Sin embargo la idea es buena y práctica. Quizás si esperamos sólo el tiempo justo es probable que lleguen una buena parte de los paquetes perdidos sinafectar significativamente el retardo. Un jitter buffer entonces es un pequeño registro donde se almacenan temporalmente todos los paquetes de vozdurante un corto tiempo para esperar por posibles paquetes perdidos. El tiempo de espera se denomina tamaño delbuffer. Asterisk soporta el concepto de jitter buffer y este parámetro es configurable a nivel de protocolos IAX y SIP. Esteparámetro se puede configurar en los archivos de tecnología correspondientes (iax.conf y sip.conf). Si se quiere estar seguro de que el jitter buffer está habilitado se puede añadir las siguientes opciones en losarchivos de tecnología. En el sip.conf: jbenable=yesjbmaxsize=200 ; Opcional (define el tamanio del buffer)

En el iax.conf: jitterbuffer=yesmaxjitterbuffer=200 ; Opcional (define el tamanio del buffer)

Page 200: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/...lo_13/13.2_Parametros_relacionados_con_calidad_de_voz_en_redes_de_paquetes.htm[24/11/2011 10:23:00 p.m.]

Esquema de funcionamiento de un jitterbuffer

Anterior Ir a índice Siguiente

Page 201: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.3_Como_medir_la_calidad_de_voz.htm[24/11/2011 10:23:02 p.m.]

Anterior Ir a índice Siguiente

13.3 Cómo medir la calidad de voz Medir la calidad de voz siempre ha sido un rompecabezas para los ingenieros. La complejidad radica en que lacalidad de voz es en parte un parámetro subjetivo de la persona que escucha. Incluso muchos conceptos como lacomprensión de una conversación telefónica varían dependiendo del idioma que usemos. Adicionalmente, nuestramente juega una serie de trucos con nosotros para “facilitarnos la vida” que hacen que ciertas mediciones de lacalidad de voz sean más difíciles de obtener. Si la voz se distorsiona justo antes de terminar la conversación esprobable que las personas califiquen la calidad de la llamada de manera diferente a que si los errores ocurrieron alprincipio de la llamada. Esto ocurre porque nuestra mente le da mas importancia a eventos más recientes que a loslejanos. También hay personas que justifican inconscientemente cierta falta de calidad de voz en pro de las ventajas oconveniencias personales percibidas. Un ejemplo de esto es que las personas no se quejan mucho de la calidad devoz en teléfonos celulares en pro de la ventaja de la movilidad. Sin embargo, si la misma calidad la escucharan enuna línea fija es probable que llamen a la compañía telefónica a quejarse porque su línea tiene mala calidad. Dichode otra manera, como seres humanos inconscientemente estamos justificando esa disminución en la calidad de vozdel teléfono celular. Esto es solo la punta del iceberg pues para calificar la calidad de voz hay una serie de parámetros subjetivos untanto difíciles de cuantificar. Lo importante de este ejemplo es ilustrar la difícil tarea que se tiene al tratar de medirla calidad de voz.Aun así, existen algunos intentos de estandarizar la medición de la calidad de voz. Uno de los más conocidos es laescala MOS que se basa en mediciones subjetivas. También podemos mencionar el modelo E que ya pone en eltapete algunos parámetros objetivos como el retardo de red o la pérdida de paquetes. Algo interesante de esteúltimo modelo es que contempla la conversión de sus resultados a la escala MOS lo que permite obtener una escalaestándar para calificar la calidad de voz.

Escala MOS La escala MOS es realmente una recomendación de la ITU. Específicamente la recomendación ITU-T P.800. Estaescala escribe una escala de calidad de voz basada en la toma de muestras subjetivas que se realizan con una seriede técnicas conocidas como Absolute Category Rating (ACR). Para tal efecto se reúne a un grupo de personas y se les pide que califiquen la calidad de voz de manera subjetiva.Antes de iniciar la evaluación se hacen escuchar algunos ejemplos que previamente han sido definidos por larecomendación de manera que los usuarios tengan algún marco referencial. Una vez hecho esto se transmite una serie de frases (también pre-definidas por la recomendación) por la líneatelefónica y los usuarios proceden a calificar la calidad de voz. El siguiente es un resumen de la escala MOS. Calificación MOS Calidad Esfuerzo5 Excelente No hace falta esfuerzo alguno4 Buena Es necesario prestar atención pero no es

necesario un esfuerzo apreciable

Page 202: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.3_Como_medir_la_calidad_de_voz.htm[24/11/2011 10:23:02 p.m.]

3 Aceptable Esfuerzo moderado2 Pobre Gran esfuerzo1 Mala No es posible entender

Una desventaja de usar la escala MOS es sin duda la cantidad de tiempo necesaria para determinar la calidad devoz de una simple línea. Imaginémonos tratando de coordinar toda una serie de pruebas con un gran grupo depersonas a quienes previamente tendremos que entrenar, y solo para evaluar la calidad de voz de una línea.

Modelo E El modelo E es un modelo más matemático y objetivo de medición de la calidad de voz basado en algunosparámetros de red como el retardo de red, pérdida de paquetes, y el jitter.

Nota: Al decir que es un método objetivo el lector no debe pensar necesariamente que este es un mejormétodo de medición de la calidad de voz. La calidad de voz contiene un importante componente subjetivocomo lo hemos mencionado anteriormente. Sin embargo, muchas veces es más práctico medir losparámetros de red y hacer un cálculo matemático para aproximar la medida de la calidad de voz en laescala MOS.

El modelo E también fue recomendado por el ITU y se trata de la recomendación ITU-T G.107. Estarecomendación dice que la calidad de voz queda representada por un parámetro R que se calcula de la siguientemanera:

R = R0 – IS – Id – Ie + A Donde,

R0 representa la relación señal-a-ruido (signal-to-noise ratio)

IS representa la degradación que sufre la señal en su conversión a paquetes Id representa el retardo de red

Ie representa la degradación introducida por los equipos de red y depende del codec y de las pérdidas de paquetes

A representa el margen de seguridad

Fórmula simplificada La recomendación ITU nos provee de una fórmula más simplificada para calcular el parámetro R. Se trata de unaaproximación menos precisa que la expresión anterior pues supone algunos valores por omisión. Esta fórmula es lasiguiente:

R = 94,2 – Id – Ie

Nota: Si somos observadores notaremos que el valor máximo que podría tomar R es de 94,2. Ya hemos definido los parámetros Id e Ie como el retardo de red y la pérdida de paquetes respectivamente. Sinembargo, antes de ingresar estos valores en la fórmula debemos normalizar estos valores de acuerdo a la

Page 203: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.3_Como_medir_la_calidad_de_voz.htm[24/11/2011 10:23:02 p.m.]

recomendación ITU. El parámetro Id representa el retardo de red y se normaliza con la siguiente fórmula.

Id = 0.024 · d + 0.11 · (d – 177.3) · H(d – 177.3) Donde d es el retardo de red en sí expresado en milisegundos y H( ) es la función de Heavyside: H(x) = 0 para x < 0 y 1 para x ≥ 0. Al analizar la fórmula de Id notaremos a primera vista que hay un valor de inflexión en los 177.3 ms. Esto quieredecir que a valores mayores que éste la calidad de voz se ve afectada a un ritmo más severo. Esto es un datointeresante ya que nos permite bosquejar una regla empírica de siempre mantener el retardo de red por debajo de170 ms (aproximadamente). Finalmente debemos calcular Ie para poder reemplazar este valor en la fórmula y calcular R. Ie dependeprincipalmente de la pérdida de paquetes y del codec usado. Para mantener las cosas relativamente simplesusaremos un gráfico con el cual podremos determinar el valor aproximado de Ie dependiendo de los dos factoresmencionados. La tabla es la siguiente:

Ie (y) vs. pérdida de paquetes (x)

Este gráfico fue generado a partir de la siguiente tabla de valores aproximados. El eje vertical representa elparámetro Ie mientras que el eje horizontal representa la pérdida de paquetes. Pérdida de paquetes%

Ie [G.711] Ie [G.723.1] Ie [G.729A]

0 0 11 151 3 15 182 5 18 204 7 20 258 9 22 2816 20 24 30

Podemos observar que mientras más compresión involucre el uso de determinado codec, mayor es la contribución

Page 204: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.3_Como_medir_la_calidad_de_voz.htm[24/11/2011 10:23:02 p.m.]

al parámetro Ie y por lo tanto menor la calidad de voz. Incluso podemos observar que con cero pérdidas depaquetes ya algunos codecs merman la calidad de voz.

Traduciendo R a la escala MOS Habiendo calculado el valor de R procedemos a explicar cómo traducirlo a la más conocida escala MOS. La fórmula es la siguiente: MOS = 1 ; R < 0

MOS = 1 + 0.035 · R + 7 · R · (R – 60) · (100 – R) · 10 -6 ; 0 < R < 100

MOS = 4.5 ; R > 100 Ahora tenemos una manera práctica y objetiva de medir la calidad de voz en una instalación de voz sobre IP. Deesta manera podremos hacer los ajustes necesarios para mejorar la satisfacción de los usuarios telefónicos. Ejemplo Supongamos que hemos realizado mediciones en un punto de la red y queremos determinar la calidad de voz endicho punto conociendo que usamos el codec G.711. El retardo de red es de 143 ms y la pérdida de paquetes llegaal 7%. ¿Cuál es la medida de calidad de voz según la escala MOS? Después de manipular los valores de acuerdo a las expresiones expuestas anteriormente, llegaremos a un valorsimilar al siguiente.

R = 94.2 – 0.024 · 143 – 7.2

R = 83.57 Traduciendo R a la escala MOS obtenemos:

MOS = 4.15 Lo cual es un resultado aceptable (4.15/5.00) pues todavía encontraremos usuarios satisfechos.

Anterior Ir a índice Siguiente

Page 205: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.4_Canceladores_de_eco.htm[24/11/2011 10:23:03 p.m.]

Anterior Ir a índice Siguiente

13.4 Canceladores de eco

Funcionamiento de canceladores de eco Es muy importante saber cómo funcionan los canceladores de eco para entender cómo sacarles provecho el máximoy quizás para diseñar el nuestro propio o modificar alguno existente en caso de ser código abierto.

Existen implementaciones de canceladores de eco tanto en hardware como en software. Generalmente se prefiereque la cancelación de eco sea implementada en hardware para no sobrecargar el procesador del servidor. Losprincipios de cancelación de eco rigen de igual forma para cualquiera de las dos implementaciones. Un cancelador de eco parte de un principio lógico muy sencillo: Si el eco significa que una parte de la señal de idase refleja en la de regreso, entonces para eliminar el eco debería bastar con restar la señal de ida (en ciertaproporción) de la señal de regreso. Debido a que el eco es una señal reflejada que se encuentra atenuada, la clave está en estimar adecuadamente dichaatenuación. Por ejemplo, supongamos que la señal de eco es un 20% de la señal original. Entonces si podemospredecir que debemos restar a la señal de regreso un 20% de la señal de ida, habremos eliminado el ecocompletamente. Al menos en teoría claro está. Esta predicción del factor de atenuación es una parte clave de todo algoritmo de cancelación de eco y recibe elnombre de algoritmo adaptativo o filtro adaptativo (adaptive filter). Se llama así porque debe adaptar el valorconstantemente para obtener los mejores resultados. En la siguiente figura supondremos que la atenuación de la señal reflejada está denotada por la letra α. La señalrecibida es Rx, la señal transmitida es Tx y la señal transmitida con el componente de eco es Txe.

Funcionamiento básico de un cancelador de eco

Sin embargo, no todo es tan sencillo como se explica aquí. El eco no es solo una señal reflejada atenuada sino quetambién puede estar desplazada en el tiempo con cierto retardo. Por lo tanto, también tenemos que predecir esteretardo para poder sustraer la señal de eco. Predecir el retardo no es una tarea sencilla y por lo general los

Page 206: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.4_Canceladores_de_eco.htm[24/11/2011 10:23:03 p.m.]

canceladores de eco tienen limitantes. Revisar la señal en busca de retardo por grandes lapsos de tiempo conllevademasiado trabajo y los canceladores de eco pueden dejar de funcionar.

Nota: Hay que hacer un pequeño paréntesis para recordar que los canceladores de eco deben funcionar entiempo real y por lo tanto no pueden perder el tiempo en cálculos complejos ya que dejarían de ser velocesy retrasarían el envío de la voz.

Los valores típicos de retardo que un cancelador de eco puede manejar son 64 ms o 128 ms. Obviamente quemientras menor sea el retardo, menor es el trabajo para el cancelador de eco (en términos de uso de CPU) peromayor podría ser la imprecisión. Este tiempo máximo de retardo que un cancelador de eco puede tolerar sedenomina comúnmente cola o tail.

El estándar G.168 Hace algunos años el ITU lanzó una especificación que define los parámetros de lo que debe ser un cancelador deeco. Se podría decir que el documento es una recomendación. Por lo tanto, si un cancelador de eco está enconcordancia con dicha recomendación se dice que es G.168 compatible (compliant with G.168). Sin embargo,G.168 es una especificación técnica compleja y es fácil determinar si un cancelador de eco es compatible o no.Inclusive existen empresas que se dedican al tedioso trabajo de revisar si un cancelador de eco es compatible o nocon G.168. No vamos a explicar aquí los detalles de G.168 pues sale del alcance del presente libro. Para mayor informaciónsobre detalles técnicos de G.168 recomendamos visitar el sitio del ITU (http://www.itu.int).

OSLEC Elastix incorpora un interesante cancelador de eco por software de libre distribución conocido como OSLEC(http://www.rowetel.com/ucasterisk/oslec.html). Este cancelador de eco es parte de DAHDI y se puede configurarindependientemente para cada canal de manera sencilla desde la interfaz Web de Elastix. Esta es una imagen de la interfaz de detección de hardware desde donde podemos activar el soporte paracancelación de eco.

Configuración de cancelador de eco en interfaz de Elastix

Page 207: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_13/13.4_Canceladores_de_eco.htm[24/11/2011 10:23:03 p.m.]

Anterior Ir a índice Siguiente

Page 208: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.1_Protocolo_SIP.htm[24/11/2011 10:23:05 p.m.]

Anterior Ir a índice Siguiente

14Protocolos VoIP al descubierto

Cualquier persona, en mar o en tierra, con un aparato sencillo y barato que cabe en un bolsillo,podría recibir noticias de cualquier parte del mundo o mensajes particulares destinados sólo al

portador, la Tierra se asemejaría, pues, a un inconmensurable cerebro, capaz de emitir unarespuesta desde cualquier punto.

-- Nikola Tesla, 1905

14.1 Protocolo SIP Session Initiation Protocol (SIP) es un protocolo de señalización (application-layer control) creado paraadministrar sesiones multimedia entre dos o más partes. Contrario a lo que se pueda pensar, este protocolo no esquien transporta la voz propiamente dicha sino que se encarga de la comunicación necesaria para establecer,modificar y finalizar una llamada. El protocolo SIP fue diseñado con la premisa de la simplicidad en mente. Se trata de un protocolo de texto conmensajes de comunicación sencillos. Inclusive SIP comparte algunos códigos de estatus con HTTP como elfamiliar “404: Not found”. SIP es un protocolo peer-to-peer. Es decir que prácticamente toda la lógica es almacenada en los puntos determinación de la llamada o endpoints.

Detalles del protocolo

Usa a su vez dos importantes protocolos:RTP transmite la voz y el videoSDP negociar las capacidades de los endpoints

Page 209: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.1_Protocolo_SIP.htm[24/11/2011 10:23:05 p.m.]

La última versión del estándar es la RFC3261.Permite entender fácilmente los mensajes transmitidos al enviarlos como texto, lo que facilita la depuración(debugging).

Señalización SIP El protocolo SIP utiliza métodos y respuestas para cumplir con su función. Un método es el mecanismo empleadopara convenir una acción. La respuesta, como su nombre lo indica, contiene la respuesta a un método.

Métodos Método DescripciónINVITE Invita a un usuario a una llamadaACK Abreviación de acknowledgement (acuse de

recibo) enviada para indicar que se harecibido un mensaje

BYE Termina una conexión entre usuarios orechaza una llamada

CANCEL Termina el requerimiento o búsqueda de unusuario

OPTIONS Solicita información acerca de lascapacidades del servidor SIP

REGISTER Registra la ubicación de un usuarioINFO Intercambia información de señalización en

el transcurso de la sesión

Respuestas

1xx Informational (e.g. 100 Trying, 180 Ringing)2xx Successful (e.g. 200 OK, 202 Accepted)3xx Redirection (e.g. 302 Moved Temporarily)4xx Request Failure (e.g. 401 Unauthorized, 404 Not Found, 482 Loop Detected)5xx Server Failure (e.g. 501 Not Implemented)6xx Global Failure (e.g. 603 Decline)

Registración El siguiente diagrama ilustra la registración de un enpoint SIP contra un servidor SIP. Debe tenerse en cuenta queesta es una vista simplificada ya que en el proceso de registración también se debe negociar el códec que seráusado además de otros parámetros.

Page 210: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.1_Protocolo_SIP.htm[24/11/2011 10:23:05 p.m.]

Registración SIP

Esta registración debe llevarse a cabo periódicamente de tal forma que durante la sesión no se tenga que enviarinformación de autenticación.

Sesión Luego de registrarse, el endpoint SIP puede iniciar una sesión (en nuestro caso una llamada telefónica). En la siguiente imagen ilustraremos el caso específico de una conversación entre dos endpoints SIP. Se hanomitido intencionalmente mensajes como ACKs para mejorar la legibilidad.

Sesión SIP entre dos teléfonos IP

Hay que notar que SIP se encarga de la señalización solamente. La voz propiamente dicha se transmite por elprotocolo RTP, el cual explicaremos con mayor detalle al final de este capítulo. Como podemos observar toda la comunicación recala en el servidor Elastix. Es decir, Elastix hace las veces demediador (SIP Proxy).

SIP y Asterisk

Page 211: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.1_Protocolo_SIP.htm[24/11/2011 10:23:05 p.m.]

Algunos detalles que debemos tener en cuenta cuando se usa el protocolo SIP con Asterisk son los siguientes:

Versiones anteriores de Asterisk (hasta 1.4 inclusive) limitaban el funcionamiento del protocolo SIP a UDP.En versiones actuales Asterisk ya podemos hacer uso de SIP inclusive sobre TCP.

Por omisión se usa el puerto 5060 para el servicio SIP aunque este parámetro se puede modificar en elarchivo sip.conf

SIP adolece de problemas de Network Address Translation (NAT) aunque se puede combatir este problemacon parámetros como externip, localnet y nat en el archivo sip_nat.conf

En Asterisk es posible hacer diagnóstico del protocolo SIP.

Anterior Ir a índice Siguiente

Page 212: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.2_Protocolo_IAX.htm[24/11/2011 10:23:06 p.m.]

Anterior Ir a índice Siguiente

14.2 Protocolo IAX El Inter-Asterisk eXchange (IAX) es un protocolo de señalización creado por Mark Spencer, el mismo creador deAsterisk. Su objetivo es el de solucionar los problemas existentes con otros protocolos. Este protocolo todavía noes un estándar en la industria pero pretende serlo a través de un proceso de estandarización en la IETF. En esencia IAX presenta dos ventajas muy interesantes sobre otras alternativas de protocolo como SIP.

Consume menos ancho de bandaSoluciona mejor los problemas de NAT y firewalls

Revisemos cada una de estas ventajas. Consume menos ancho de banda Mientras SIP es un protocolo basado en texto, IAX es un protocolo binario. Esto es una ventaja desde el punto devista del consumo de ancho de banda puesto que en binario se desperdiciarán menos bytes. Además, el protocoloIAX permite la troncalización de varios canales de audio en el mismo flujo de datos. Es decir que en un mismodatagrama se pueden enviar varias sesiones al mismo tiempo. Esto significa una reutilización de datagramas y porconsiguiente un ahorro adicional de ancho de banda. Soluciona mejor los problemas de NAT y firewalls SIP transmite señalización por el puerto 5060 y usa pares de puertos entre el 10000 y 20000 para la voz en sí. Estaseparación de puertos tiende a causar problemas al pasar la comunicación de voz por un firewall. En cambio IAXtransmite en UDP y usa solamente el puerto 4569 para transmitir tanto la señalización como la voz. Esto permiteconducir comunicaciones a través de firewalls con mucha más facilidad. El administrador debe asegurarse de abrirun solo puerto en el firewall. Además, el endpoint IAX no necesita saber nada sobre la red en la cual está operando.Esta combinación de atributos hace que se elimine el caso donde la llamada se completa pero el audio no pasa. Si reflexionamos acerca de estas ventajas nos daremos cuenta rápidamente que resultan perfectas paratroncalización entre dos servidores Elastix. En otras palabras, cuando se trata de interconectar dos o más servidoresElastix entre sí el uso de IAX es altamente recomendable.. La versión actual del protocolo IAX es la 2. La anterior ha quedado obsoleta por lo que es común ver el nombreIAX2 como sinónimo de IAX.

Fases de una llamada IAX Una llamada IAX tiene tres fases que se explican a continuación.

Establecimiento de la llamada

Page 213: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.2_Protocolo_IAX.htm[24/11/2011 10:23:06 p.m.]

Para iniciar una llamada el equipo que la inicia (equipo A) le envía un mensaje NEW al equipo que la recibe(equipo B). Éste último responde con un mensaje ACCEPT. Luego de esto el equipo B timbrará su campanaesperando que el usuario levante el auricular. Si esto sucede, el equipo B enviará un mensaje ANSWER al equipoA para notificar que el usuario contestó.

Nota: Se han omitido intencionalmente algunos mensajes ACK en esta explicación para añadir claridad ala explicación.

Establecimiento de una llamada IAX

Llamada en curso Una vez contestada la llamada por el equipo B se inicia el intercambio de audio mediante unos paquetes llamadosframes. Estos frames se envían dentro del mismo flujo de comunicación que la señalización inicial.

Colgado Cualquiera de las partes involucradas en la conversación puede enviar un mensaje HANGUP para terminar lallamada en cualquier momento.

Colgado de una llamada IAX

Page 214: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.2_Protocolo_IAX.htm[24/11/2011 10:23:06 p.m.]

Frames Para intercambiar el audio entre los participantes de una llamada se pueden utilizar dos tipos de frames específicospara IAX llamados full y mini. También se les suelen llamar F y M por sus iniciales. Una conversación está compuesta en su mayoría por frames de tipo mini, cuya virtud es (como su nombre losugiere) ser pequeños y ligeros. Esto quiere decir que tienen una cabecera pequeña de 4 bytes, lo cual ayuda aahorrar ancho de banda. De cuando en cuando se intercambian frames tipo full, los cuales conllevanadicionalmente información de sincronización para mantener sincronizados a ambos puntos. 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| Número de Origen |R| Número de Destino | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time-stamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | OSeqno | ISeqno | Tipo Frame |C| Subclass | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | : Data : | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Frame de tipo full

1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| Número de Origen | time-stamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | : Data : | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Frame de tipo mini

Anterior Ir a índice Siguiente

Page 215: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.3_Protocolo_RTP.htm[24/11/2011 10:23:07 p.m.]

Anterior Ir a índice Siguiente

14.3 Protocolo RTP RTP es el protocolo que se encarga de transportar la voz propiamente dicha. Muchas personas se confunden ypiensan que ese es el trabajo de SIP pero no es así. Como ya lo hemos visto anteriormente en este capítulo, una vezque SIP establece una llamada es RTP quien toma la posta para transportar la voz a su destino. RTP trabaja sobre UDP y por lo tanto no hay mucho control de transmisión. Es decir que el equipo emisor envía lavoz hacia el otro extremo con solo la esperanza de que llegue. Por tanto no espera recibir confirmación del mensajerecibido ya que la voz necesita ser transmitida en tiempo real y cualquier demora puede comprometer la calidad devoz. Si un paquete de voz se pierde en el camino simplemente se rellenará ese espacio con un silencio. Lo quetécnicamente se llama ruido confortable (comfort noise). Es por esta necesidad de transmitir la información en tiempo real que resulta obvio que RTP sea un acrónimo deReal Time Protocol. RTP cuenta con la ayuda de otro protocolo llamado RTCP. Este protocolo no es del todo indispensable peroproporciona valiosa ayuda al momento de transportar la voz de manera óptima ya que proporciona estadísticas einformación de control. Esta información a su vez le permite a los equipos de voz involucrados en la conversacióntomar decisiones para mejorar la transmisión en caso de ser posible. Para este efecto los paquetes RTCP setransmiten periódicamente.

Estructura de un paquete RTP Un paquete RTP se compone de un encabezado y la data o payload. El siguiente diagrama ilustra la estructura delencabezado de los paquetes RTP.

Byte 1 Byte 2 Byte 3 Byte 4V=2 P X CC M PT Número de Secuencia

TimestampFuente de Sincronización (SSRC)

Fuente Contribuyente (CSRC)Extensión (Opcional dependiendo del bit X)

Data Estos campos se definen de la siguiente forma.

V es el número de versión. Este campo es de 2 bits de longitud y su valor siempre es el número 2.P es un bit que indica si hay relleno o padding al final de la data. El relleno no es otra cosa que bytesadicionales al final del payload utilizados para ciertos algoritmos de encriptación que esperan un payload detamaño fijo.X o extensión es un bit que indica si hay extensión del encabezadoCC es un identificador de 4 bits que indica el conteo CSRCM o marcador de un bit

Page 216: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.3_Protocolo_RTP.htm[24/11/2011 10:23:07 p.m.]

PT o tipo de carga útil (payload type) es un identificador de 7 bits que nos indica el tipo de carga útil quecontiene este paquete RTP. Ejemplos de tipos son G729, GSM, PCMU (G711 u-law), entre otros.Número de Secuencia (sequence number) es un número entero que identifica cada paquete del presente flujode datos. Este es un identificador secuencial que se incrementa en uno con cada paquete transmitido. Ocupa16 bits.Timestamp representa el instante de tiempo en el que se comenzó a muestrear la data que está siendotransmitida en el payload. Ocupa 32 bits.SSRC identifica la fuente de sincronización ya que el mismo equipo puede estar comunicándose condiferentes fuentes de paquetes RTP. Es un número aleatorio de 32 bits por lo que hay la posibilidad (aunquesea baja) de que este número se repita entre dos fuentes. Existen mecanismos para resolver este problema.CSRC es un número de 32 bits que identifica las fuentes contribuyentes para el payload.Extensión es un campo de longitud variable que permite extender la funcionalidad de la cabecera. Estainformación solo se adjunta a la cabecera RTP si el bit X lo indica.

Luego de la cabecera se deben transmitir los datos que no son otra cosa que el audio propiamente dicho convertidoa digital y codificado. Cabe recordar que RTP utiliza dos puertos para la comunicación, uno de ida y otro para el retorno. Este par depuertos es negociado mientras se establece la llamada entre los puntos pero en el caso de Asterisk está dentro delrango 10000 a 20000. Sin embargo, esto es configurable en el archivo /etc/asterisk/rtp.conf.

Anterior Ir a índice Siguiente

Page 217: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_14/14.4_Protocolo_SRTP.htm[24/11/2011 10:23:08 p.m.]

Anterior Ir a índice Siguiente

14.4 Protocolo SRTP SRTP o RTP seguro (Secure Real-time Protocol) es, como su nombre lo indica, un alternativa a RTP cuandonecesitamos cifrar la información transmitida. En nuestro caso se vuelve muy útil cuando se necesita garantizar queuna llamada no podrá ser escuchada por un interceptor de la misma, manteniendo la información confidencial. Desde el punto de vista de un protocolo de tiempo real se hace un poco difícil concebir un cifrado de datos que noañada retardo a la comunicación. Si cada paquete debe ser encriptado en el origen y des-encriptado en destino, sinduda esto debe añadir un retardo adicional, dependiendo de la potencia de nuestro CPU que es quien realizará lamatemática necesaria para el cifrado de datos. Además también podemos pensar que el uso de algoritmos decifrado añadirá ancho de banda adicional, lo cual siempre es indeseable. Todos los temores anteriores son válidos y también estuvieron en la mente de quienes diseñaron el protocolo. Espor eso que si leemos el documento oficial donde se define este protocolo (RFC 3711) veremos que aparte de losobjetivos obvios de SRTP (confidencialidad de información e integridad de datos) se definen estos otros:

• Bajo impacto en el ancho de banda• Bajo costo computacional

En general podemos decir que hicieron un buen trabajo y el protocolo no añade un costo computacional o ancho debanda significativo por lo que en la gran mayoría de escenarios podremos implementar SRTP sin ningún temor. SRTP está disponible de manera nativa en Asterisk recién desde la versión 1.8 y habilitarlo es bastante sencillo.Por ejemplo, si la comunicación es SIP basta añadir a la configuración de cada endpoint el parámetroencryption=yes

Anterior Ir a índice Siguiente

Page 218: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.1_Interpretando_el_log.htm[24/11/2011 10:23:10 p.m.]

Anterior Ir a índice Siguiente

15Diagnóstico básico de problemas

Si hubiera preguntado a mis clientes qué necesitaban, habrían dicho un caballo mejor-- Henry Ford, fundador de Ford Motor Company

15.1 Interpretando el log Es muy importante entender cómo leer los archivos de log de Asterisk puesto que de allí podemos extraerinformación muy valiosa en nuestro proceso de diagnóstico. El nivel de detalle así como el tipo de información que se escribe en los archivos de log son controlados desde elarchivo /etc/asterisk/logger.conf. Este es un archivo de texto plano donde se definen tanto el nombrede los archivos de log como el nivel de detalle de la información que se escribirá en ellos. Esto se hace en una solalínea con la siguiente sintaxis. Nombre de archivo => Niveles de debugging

Donde los niveles de debugging son separados por coma y pueden ser los siguientes:

debugnoticewarningerrorverbose

Page 219: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.1_Interpretando_el_log.htm[24/11/2011 10:23:10 p.m.]

Nota: Hay un tipo especial de nombre de archivo que se encuentra reservado y que se llama "console". Estenombre representa la consola de Asterisk, o sea lo que se muestra en el Asterisk CLI.

El siguiente es un fragmento del contenido del archivo logger.conf que se distribuye con Elastix. ; Directory for log files is configures in asterisk.conf; option astlogdir;[logfiles];; Format is "filename" and then "levels" of debugging to be included:; debug; notice; warning; error; verbose;; Special filename "console" represents the system console;;debug => debug; The DTMF log is very handy if you have issues with IVR’s;dtmf => dtmf;console => notice,warning,error;console => notice,warning,error,debug;messages => notice,warning,errorfull => notice,warning,error,debug,verbose

En el ejemplo anterior vemos algunas líneas comentadas y básicamente un solo archivo de log activado llamadofull. Este, al igual que los demás archivos definidos de esta manera reside en la ruta /var/log/asterisk/.

El archivo /var/log/asterisk/full Acorde al archivo logger.conf, Elastix habilita por defecto el archivo de log llamado full donde Asteriskescribe información de su funcionamiento. Cada línea de este archivo tiene el siguiente formato. [HORA FECHA] NIVEL[PID] NOMBRE_DE_ARCHIVO: MENSAJE A continuación veremos un ejemplo del archivo de log de Asterisk.

Page 220: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.1_Interpretando_el_log.htm[24/11/2011 10:23:10 p.m.]

Archivo de log /var/log/asterisk/full

Monitoreo del log Es muy importante dar seguimiento en tiempo real a la actividad del servidor Elastix. Muchas veces nos veremoshaciendo esto mientras realizamos o recibimos una llamada para tratar de averiguar qué ha fallado. El siguiente es un método útil para revisar interactivamente el archivo de log full a medida que se va escribiendocon mensajes de Asterisk. tail -f /var/log/asterisk/full

Si queremos ver interactivamente solo los errores podemos añadir el siguiente filtro. tail -f /var/log/asterisk/full | grep ERROR

Si queremos además ver las advertencias podemos modificar ligeramente el filtro de la siguiente manera. tail -f /var/log/asterisk/full | grep -E "(ERROR|WARNING)"

Nota: Si queremos examinar todo el log en lugar de hacerlo interactivamente debemos reemplazar elcomando tail -f por el comando cat

¿Qué información nos puede indicar el campo MENSAJE? El MENSAJE se refiere a la información que viene a la derecha de cada línea del log luego del nombre delarchivo. Si se trata de una línea de ERROR o WARNING encontraremos aquí una breve descripción del errorocurrido o de la advertencia. Sin embargo existen otras líneas con mensajes menos obvios y que simplementedescriben el procesamiento de una llamada a través del plan de marcado. Estas líneas normalmente se encuentranmacadas con nivel VERBOSE pues son simplemente informativas. Estas líneas de nivel VERBOSE (además de otras líneas informativas) nos proveen de información muy útil paradiagnosticar problemas.

Page 221: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.1_Interpretando_el_log.htm[24/11/2011 10:23:10 p.m.]

Especialmente útiles son las que empiezan con la palabra Excecuting ya que a continuación mencionan el contextoy la prioridad en el que Asterisk está procesando el plan de marcado. La sintaxis de estas líneas es la siguiente. [TIME DATE] VERBOSE[PID] logger.c: -- Excecuting[extension@contexto:prioridad] MAS_TEXTO MAS_TEXTO puede contener información acerca de la aplicación que fue ejecutada junto con los parámetros que lefueron pasados. Veamos un ejemplo de esto. [Oct 28 17:52:34] VERBOSE[22034] logger.c: -- Executing [s@macro-dial:7]Dial("Local/502@from-internal-e27c,2", "SIP/502|21|trTWuwM(auto-blkvm)") in newstack

En este ejemplo vemos que cuando se escribió esta línea en el log nos encontrábamos dentro del contexto macro-dial (una macro, ya que empieza con la palabra macro). Además, la extensión era la s y la prioridad era 7. Tambiénpodemos observar que se está tratando de marcar mediante la aplicación Dial() usando ciertos parámetros. En fin,podemos observar que hay mucha información útil que podemos obtener de cada línea escrita en el log.

Número de proceso (PID) Asterisk es un software multiproceso. Esto quiere decir que puede crear varias instancias de sí mismo que trabajende manera coordinada entre sí para ejecutar diferentes tareas al mismo tiempo. Cuando Asterisk escribe una líneaen el log también anota el número de proceso (PID) que la escribió. Esto nos provee valiosa información puestoque podemos tener una visión más exacta del hilo de la llamada. Para hacer esto podemos filtrar el PID si es que loconocemos. cat /var/log/asterisk/full | grep 38484

Con el comando anterior estamos filtrando la salida para mostrar el proceso 38484. Por supuesto que tambiénpodremos haber capturado alguna cadena de caracteres que coincida fortuitamente con el patrón 38484. Sinembargo estas líneas son irrelevantes y se las puede eliminar manualmente. Gracias a este procedimiento podremos filtrar el hilo de una llamada y aislarlo para encontrar errores. Esto esparticularmente útil en un ambiente con alto número de llamadas simultáneas debido a la gran cantidad deinformación que Asterisk escribe en el log.

Nota: Algo importante a tener en cuenta es que una llamada puede tener más de un proceso (y porconsiguiente PID) involucrado.

Anterior Ir a índice Siguiente

Page 222: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.2_Diagnostico_a_traves_del_CLI.htm[24/11/2011 10:23:11 p.m.]

Anterior Ir a índice Siguiente

15.2 Diagnóstico a través del CLI Desde el Asterisk CLI podemos ver en tiempo real el funcionamiento de Asterisk. Es algo similar a hacer un"tail -f /var/log/asterisk/full" pero con la ventaja de poder ver el texto de salida resaltado (paramejor legibilidad). Además el CLI nos permite interactuar simultáneamente con Asterisk al poder ejecutar algunoscomandos desde la consola. Elastix nos brinda una interfaz directa al Asterisk CLI ubicada en PBX->Tools y basada en Web. Usar el CLIdesde la interfaz Web puede resultar muy cómodo al no tener que iniciar una sesión SSH, la cual muchas veces seencuentra restringida para conexiones remotas. Lo que hay que tener en cuenta es que desde la interfaz Web no esposible tener un CLI interactivo. Esta es la principal diferencia de ejecutar el CLI desde la línea de comandos aejecutarlo desde Web. Para acceder al CLI desde la línea de comandos es necesario ejecutar lo siguiente. asterisk -r

A continuación un ejemplo de ejecución del comando “help” desde la interfaz Web de Elastix.

Ejecutando el CLI a través de la interfaz Web de Elastix

Anterior Ir a índice Siguiente

Page 223: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_15/15.3_Sniffing.htm[24/11/2011 10:23:12 p.m.]

Anterior Ir a índice Siguiente

15.3 Sniffing El término sniffing describe la forma de capturar paquetes de red en su formato original para su posterior análisis.Existen herramientas especializadas para este fin y algunas cuestan una verdadera fortuna. Por suerte haysoluciones de código abierto que hacen un gran trabajo como es el caso de Wireshark. Wireshark era anteriormente conocido como Ethereal. Este poderoso sniffer contiene herramientas de análisisavanzadas que nos permitirán analizar paquetes RTP y SIP entre otras cosas. Para capturar los detalles de una llamada y analizarla debemos primero definir la tarjeta de red del servidor en lacual queremos escuchar si existe más de una. La captura de paquetes en sí es muy sencilla y solo debemos ejecutarWireshark de acuerdo a sus instrucciones. Finalizada la captura lo más probable es que junto con los paquetes de voz hayamos capturado otros paquetes quecirculaban por la red. Muchos de estos paquetes como ICMP, DNS, y SMTP no son de nuestro interés pero conalgo de práctica aprenderemos a filtrar estos paquetes irrelevantes.

Anterior Ir a índice Siguiente

Page 224: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.1_Asterisk_AGI.htm[24/11/2011 10:23:13 p.m.]

Anterior Ir a índice Siguiente

16Control externo de Asterisk

Más que exigirlo, el respeto es algo que uno se gana-- Anónimo

Muchas veces editar el plan de marcado no es suficiente y hace falta algún mecanismo más flexible para lograr loque la empresa necesita. En otras ocasiones quisiéramos inclusive poder controlar Asterisk en tiempo real a travésde alguna aplicación remota. Para expandir el comportamiento de Asterisk más allá del plan de marcado existen dos interfaces muy útilesllamadas AGI y AMI., Estas interfaces nos permiten interactuar con Asterisk a un nivel mucho más poderoso queel logrado hasta ahora.

16.1 Asterisk AGI Asterisk Gateway Interface (AGI) establece una manera de interactuar con Asterisk desde un programa de línea decomandos. Este programa puede ser escrito en prácticamente cualquier lenguaje de programación y es invocado porAsterisk desde el plan de marcado o dialplan. Al momento de la invocación de un programa AGI se le pasan ciertos parámetros y este a su vez responde concomandos AGI que son entendidos por Asterisk. La utilidad de AGI es enorme y nos permite desarrollar funcionalidad extra para nuestra central telefónica. Unejemplo muy común de esto es el desarrollo de aplicaciones de consulta telefónica a bases de datos. Los programas o scripts AGI gozan de mucha popularidad. Elastix viene por defecto con algunos de estos scriptspreinstalados en la carpeta /var/lib/asterisk/agi-bin/

Page 225: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.1_Asterisk_AGI.htm[24/11/2011 10:23:13 p.m.]

Ejecución de scripts AGI Los scripts AGI se comunican con Asterisk a través de los descriptores de archivos STDIN, STDOUT y STDERR.Esto quiere decir que deberían poderse ejecutar desde la misma línea de comandos. Algo muy importante de mencionar es que los scripts AGI deben tener permisos de ejecución para el usuarioasterisk y el grupo del mismo nombre para que puedan correr. Podemos asignar los permisos de la siguienteforma. # chown asterisk.asterisk script_prueba.agi# chmod 755 script_prueba.agi

Luego de esto ya podemos ejecutar el script AGI desde el dialplan para que haga algo útil. Esto se lo hace graciasa la función AGI(). A continuación un ejemplo. exten => 6789,1,Answerexten => 6789,2,AGI(script_prueba.agi)

Como vemos en el ejemplo anterior le hemos dicho a Asterisk que ejecute el script llamadoscript_prueba.agi. Este script se ejecutará cuando el usuario digite la extensión 6789. Por omisión Asteriskasume que el script se encuentra en la ruta /var/lib/asterisk/agi-bin/ aunque se puede especificar otraruta en la función AGI().

Parámetros enviados al script AGI Como habíamos dicho antes, Asterisk le envía cierta información al script AGI al momento de su invocación. Acontinuación un ejemplo de la información enviada al script dialparties.agi que es un componente deFreePBX cuando lo ejecutamos. agi_request: dialparties.agiagi_channel: SIP/4444-08d6ab60agi_language: enagi_type: SIPagi_uniqueid: 1222117320.271agi_callerid: 4444agi_calleridname: Edgar Landivaragi_callingpres: 0agi_callingani2: 0agi_callington: 0agi_callingtns: 0agi_dnid: 216 6agi_rdnis: unknownagi_context: macro-dialagi_extension: sagi_priority: 3agi_enhanced: 0.0agi_accountcode:

Page 226: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.1_Asterisk_AGI.htm[24/11/2011 10:23:13 p.m.]

Adicionalmente a la información que Asterisk le envía al script AGI por omisión, nosotros podríamos enviarleinformación adicional invocando la función AGI() con ciertos parámetros de la siguiente manera. exten => 6789,1,Answerexten => 6789,2,AGI(script_prueba.agi,param1,param2,param3)

En el ejemplo anterior se le envían los parámetros adicionales param1, param2 y param3 al script. El script puederecibir tantos parámetros como sean necesarios.

Comandos AGI Para la referencia del lector, a continuación mostramos un listado de los comandos AGI disponibles en la últimaversión de Elastix. Este listado ha sido generado con el comando agi show commands desde el CLI. Comando Descripciónanswer Contesta el canalasyncagi break Interrumpe el Async AGIchannel status Retorna el estado del canal conectadodatabase del Elimina clave/valor de la base de datosdatabase deltree Elimina clave de árbol/valor de la base de

datosdatabase get Obtiene un valor de la base de datosdatabase put Añade/actualiza un valor de la base de datosexec Ejecuta una aplicaciónget data Escucha por tonos DTMF en un canalget full variable Evalúa una expresión de canalget option Stream de archivo, escucha por DTMF, con

timeoutget variable Obtiene una variable de canalhangup Cuelga el canal actualnoop No hace nadareceive char Recibe un caracter de los canales que lo

soportenreceive text Recibe texto de los canales que lo soportenrecord file Graba a un archivosay alpha Vocaliza una cadena de caracteressay digits Vocaliza una cadena de dígitossay number Vocaliza númerossay phonetic Vocaliza una cadena de caracteres

fonéticamentesay date Vocaliza una fechasay time Vocaliza una horasay datetime Vocaliza una hora en un formato especificosend image Envía imágenes a canales que lo soportensend text Envía texto a canales que lo soporten

Page 227: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.1_Asterisk_AGI.htm[24/11/2011 10:23:13 p.m.]

set autohangup Auto-cuelga el canal después de un tiemposet callerid Especifica el callerid para el canal actualset context Especifica el contexto para el canalset extension Cambia la extensión del canalset music Habilita/Deshabilita el generador de música

de esperaset priority Especifica la prioridad en el plan de

marcado para el canalset variable Especifica una variable de canalstream file Envía un archivo de audio en el canalcontrol stream file Envía un archivo de audio en el canal y

permite al receptor controlar el streamtdd mode Cambia el modo de TDD (para sordos)verbose Escribe en mensaje en el archivo de log

verbose de Asteriskwait for digit Espera el ingreso de un digitospeech create Crea un objeto de reconocimiento de voz

(speech)speech set Especifica una opción del motor de

reconocimiento de vozspeech destroy Destruye un objeto de reconocimiento de

voz (speech)speech load grammar Carga un vocabulariospeech unload grammar Descarga un vocabulariospeech activate grammar Activa un vocabulariospeech deactivate grammar Desactiva un vocabulariospeech recognize Reconoce la vozgosub Ejecuta una subrutina del plan de marcado

Librerías AGI A pesar de que un script AGI puede ser escrito prácticamente en cualquier lenguaje, existen algunos lenguajes queya cuentan con librerías para facilitar las labores de desarrollo. Algunos de estos lenguajes son los siguientes.

PerlPHPPythonRubyC.NET

Para mayor información sobre las librerías o frameworks disponibles para estos lenguajes recomendamos revisar elsiguiente vínculo: http://www.voip-info.org/wiki-Asterisk+AGI En nuestro caso utilizaremos una librería para PHP llamada phpAGI con la que codificaremos un sencillo script

Page 228: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.1_Asterisk_AGI.htm[24/11/2011 10:23:13 p.m.]

AGI de ejemplo en la siguiente sección.

Ejemplo sencillo de script AGI Para ilustrar mejor el funcionamiento de un script AGI, codificaremos algo muy básico. Este script vocaliza unnúmero cuando marcamos una extensión determinada. A continuación el código en PHP. #!/usr/bin/php -q <?php echo "SAY NUMBER 1234 \n"; sleep(4); ?>

Este código lo podemos guardar como simple.agi en la ruta estándar /var/lib/asterisk/agi-bin/ Una vez guardado debemos estar seguros que el script pueda ser ejecutado por el usuario asterisk del grupoasterisk. Como lo hemos explicado anteriormente, esto se consigue de la siguiente manera. chown asterisk.asterisk /var/lib/asterisk/agi-bin/simple.agichmod 755 /var/lib/asterisk/agi-bin/simple.agi

Finalmente debemos modificar el plan de marcado para invocar nuestro script AGI cuando se marque unaextensión determinada. Usaremos la extensión 6789 para este ejemplo. exten => 6789,1,Answerexten => 6789,2,AGI(simple.agi)exten => 6789,3,Hangup

Estas instrucciones podrían ubicarse al final del archivo /etc/asterisk/extensions_custom.conf, yaque este archivo no es sobrescrito por FreePBX. ¡Listo! Marque la extensión 6789 y escuchará el código decir “one two three four”.

Anterior Ir a índice Siguiente

Page 229: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

Anterior Ir a índice Siguiente

16.2 Asterisk AMI El Asterisk Manager Interface (AMI) establece una manera de comunicarse con Asterisk a través del protocolo IP. Digamos que esun concepto similar al AGI pero orientado para su ejecución desde equipos remotos. Es esto último lo que lo convierte en unaherramienta poderosa. Con la funcionalidad que provee AMI se pueden desarrollar poderosas aplicaciones cliente que pueden ejecutarse en otroscomputadores liberando de carga al servidor Asterisk. Un ejemplo de lo que se puede hacer con AMI es el módulo para call centersque forma parte del proyecto Elastix. Este módulo de Elastix está codificado en gran parte usando AMI. Debido a que AMI permite que equipos remotos controlen el funcionamiento de Asterisk, se requiere que estos equipos seautentiquen. Los usuarios, claves y permisos se definen en un archivo llamado /etc/asterisk/manager.conf A continuación reproducimos parte del archivo manager.conf que se distribuye con Elastix por defecto. ;; AMI - Asterisk Manager interface;[general]enabled = yesport = 5038bindaddr = 0.0.0.0 [admin]secret = elastix456deny=0.0.0.0/0.0.0.0permit=127.0.0.1/255.255.255.0read =system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originatewrite =system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate #include manager_additional.conf#include manager_custom.conf

En este archivo se define un usuario llamado admin con clave elastix456 que puede conectarse desde la dirección IP 127.0.0.1con máscara 255.255.255.0. Luego de esto se definen ciertos permisos para este usuario.

Probando desde telnet Para probar la interacción con AMI no es necesario de un programa sofisticado. Una manera sencilla de hacerlo es a través delprograma telnet disponible en cualquier computador. Veamos un ejemplo ejecutando este comando desde el propio servidor Elastix y suponiendo el archivo de configuración anterior. Primero nos conectamos al propio servidor Elastix a través de una sesión telnet. Para esto ejecutamos lo siguiente desde la líneade comandos. [root@elastix ~]# telnet 127.0.0.1 5038Trying 127.0.0.1...Connected to localhost.localdomain (127.0.0.1).Escape character is '^]'.Asterisk Call Manager/1.1

Page 230: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

Como podemos ver el servidor nos ha contestado con un mensaje indicando que el AMI está escuchando y nos dice también que setrata de la versión 1.1 del protocolo. A continuación nos autenticamos con el usuario y clave especificado en el archivo manager.conf. Básicamente debemos escribirlos siguiente en el terminal. Action: LoginActionID: 1Username: adminSecret: elastix456

Es importante conocer que luego de escribir lo anterior y para enviar el comando debemos ingresar dos retornos de carro. Es decirque debemos presionar Enter dos veces para enviar la petición de autenticación anterior. Luego de esto AMI nos contestará con unmensaje de éxito o error. El siguiente es el mensaje que obtenemos como exitoso. Response: SuccessActionID: 1Message: Authentication accepted

De ahora en adelante comenzarán a aparecer mensajes de registro que el AMI envía a nuestra sesión cada vez que ocurre un evento.Por ejemplo, recibimos estos mensajes cuando una llamada se termina o si una extensión está timbrando. Una vez autenticada la sesión podemos ejecutar comandos, también llamados acciones, directamente vía AMI.

Tipo de paquetes AMI En la comunicación por AMI se pueden identificar tres tipos de paquetes de información.

Acción: Un comando enviado por el cliente al servicio AMI para que sea procesado.Respuesta: La respuesta de Asterisk a la acción requerida por el cliente.Evento: La información de un evento asincrónico ocurrido en Asterisk. Por ejemplo, la llegada de una llamada telefónica.

Para relacionar las respuestas con las acciones se puede incluir un ActionID en cada acción. Asterisk devolverá este parámetro en larespuesta.

Comandos o acciones AMI El siguiente listado de comandos AMI se obtiene al ejecutar el comando manager show commands desde el CLI de Elastix. Comando Privilegios Descripción

AbsoluteTimeout system,call,all

Especifica eltimeoutabsoluto

AgentLogoff agent,all

Especifica queun usuario hadejado de estarautenticado

Agents agent,all

Enlista losagentes y susestadosAñade uncomando AGI

Page 231: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

AGI agi,all

para ejecucióncon AsyncAGI

Atxfer call,allTransferenciaatendida

Bridge call,all

Conecta doscanalespresentes en elPBX

Challenge <none>

Genera reto(challenge)paraautenticaciónde MD5

ChangeMonitor call,all

Cambia elarchivo demonitoreo deun canal

Command command,all

Ejecuta uncomando delCLI

CoreSettings system,reporting,all

Muestraconfiguracióndel core delPBX (versión,etc)

CoreShowChannels system,reporting,all

Enlista loscanales activosactualmente

CoreStatus system,reporting,all

Muestra lasvariables deestado del coredel PBX

CreateConfig config,all

Crea unarchivo vacíoen eldirectorio deconfiguración

DAHDIDialOffhook <none>

Marcar sobreun canalDAHDImientras estáen offhook

DAHDIDNDoff <none>

Cambia elestado de nomolestar(DND) delcanal DAHDIa OFF

DAHDIDNDon <none>

Cambia elestado de nomolestar(DND) delcanal DAHDIa ON

DAHDIHangup <none>Termina elcanal DAHDIReiniciacompletamentelos canalesDAHDI

Page 232: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

DAHDIRestart <none>(termina todaslas llamadas)

DAHDIShowChannels <none>

Muestra elestado de loscanalesDAHDI

DAHDITransfer <none>Transfiere uncanal DAHDI

DBDel system,all

Elimina unregistro de labase de datos

DBDelTree system,all

Elimina unárbol de labase de datos

DBGet system,reporting,all

Obtiene unregistro de labase de datos

DBPut system,all

Ingresa unregistro en labase de datos

Events <none>

Controla elflujo de unevento

ExtensionState call,reporting,all

Verifica elestado de unaextensión

GetConfig system,config,allObtiene laconfiguración

GetConfigJSON system,config,all

Obtiene laconfiguraciónen formatoJSON

Getvar call,reporting,all

Obtiene unavariable decanal

Hangup system,call,allTermina elcanal

IAXnetstats system,reporting,all

Muestra lasestadísticas dered de IAX

IAXpeerlist system,reporting,allEnlista lospeers de IAX

IAXpeers system,reporting,allEnlista lospeers de IAX

IAXregistry system,reporting,all

Muestra laregistracionesde IAX

ListCategories config,all

Enlista lascategorías delarchivo deconfiguración

ListCommands <none>

Enlista loscomandos demanager(AMI)disponibles

Login <none>Inicia la sesióndel ManagerTermina la

Page 233: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

Logoff <none>sesión delManager

MailboxCount call,reporting,all

Revisa elnúmero demensajes en elbuzón

MailboxStatus call,reporting,allRevisa elbuzón

MeetmeList reporting,all

Enlista losparticipantesen unaconferencia

MeetmeMute call,all

Calla unusuario deMeetme

MeetmeUnmute call,all

Permite hablara un usuariode Meetme

ModuleCheck system,all

Verifica si unmódulo estácargado

ModuleLoad system,allCarga unmódulo

Monitor call,allMonitorea uncanal

Originate originate,allOrigina unallamada

Park call,allParquea uncanal

ParkedCalls <none>

Enlista lasllamadasparqueadas

PauseMonitor call,all

Pausa elmonitoreo deun canal

Ping <none>

Comando paramanteneractiva laconexión

PlayDTMF call,all

Reproduceseñal DTMFen un canalespecífico

QueueAdd agent,all

Añade unainterface a lacola

QueueLog agent,all

Añade unrecordpersonalizadoen elqueue_log

QueuePause agent,all

Establece unmiembro deuna cola comotemporalmenteno disponible

QueuePenalty agent,all

Establece lapenalidad paraun miembro deuna cola

Page 234: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

QueueReload <none>

Recarga unacola, colas, ocualquier sub-sección de unacola o colas

QueueRemove agent,all

Elimina unainterface de lacola

QueueReset <none>

Vacía lasestadísticas dela cola

QueueRule <none>Reglas de lacola

Queues <none> Colas

QueueStatus <none>Estado de lacola

QueueSummary <none>Resumen de lacola

Redirect call,all

Redirige(transfiere)una llamada

Reload system,config,all

Envía unevento derecarga

SendText call,all

Envía unmensaje detexto al canal

Setvar call,all

Establece unavariable decanal

ShowDialPlan config,reporting,allEnlista el plande marcado

SIPnotify system,all

Envía unanotificación deSIP

SIPpeers system,reporting,all

Enlista lospeers de SIP(formato texto)

SIPqualifypeer system,reporting,all

Muestra lospeers de SIP(formato texto)

SIPshowpeer system,reporting,all

Muestra lospeers de SIP(formato texto)

SIPshowregistry system,reporting,all

Muestra lasregistracionesSIP (formatotexto)

Status system,call,reporting,all

Enlista elestado delcanal

StopMonitor call,all

Termina elmonitoreo deun canal

UnpauseMonitor call,all

Libra de pausael monitoreode un canalActualiza laconfiguración

Page 235: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/capitulo_16/16.2_Asterisk_AMI.htm[24/11/2011 10:23:14 p.m.]

UpdateConfig config,all básica

UserEvent user,all

Envía uneventoarbitrario

VoicemailUsersList call,reporting,all

Enlista toda lainformaciónde usuarios devoicemail

WaitEvent <none>

Espera a queun ocurraevento

Anterior Ir a índice Siguiente

Page 236: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

Anterior Ir a índice

AArchivos de configuración de Asteriskdistribuidos con Elastix Archivo Descripcióna2billing.conf Archivo general de configuración de

A2billing.additional_a2billing_iax.conf Configuración de IAX para A2billing.additional_a2billing_sip.conf Configuración de SIP para A2billing.adsi.conf Archivo de configuración para ADSI

(Interfaz Análoga para servicios de Displaypor sus siglas en Inglés). Con ADSI sepuede interactuar entre Asterisk y losdisplays de teléfonos análogos.

adtranvofr.conf Archivo de configuración que permite tenersoporte de Voz sobre Frame Relay

agents.conf Archivo de configuración que permitemanejar los agentes de las colas.

alarmreceiver.conf Sirve para configurar la aplicaciónAlarmReciever().

alsa.conf Configura el driver de sonido con losdrivers de ALSA.

amd.conf Se utiliza para detección automática demáquinas contestadoras.

applications.conf Básicamente aquí se incluye plan demarcado. Los contextos aquí incluidos seles puede denominar aplicaciones y susnombres empiezan con la cadena “app-“.

asterisk.conf Archivo principal de configuración de

Page 237: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

Asterisk. Aquí se configuran los directoriosde trabajo de Asterisk así como algunasopciones generales.

cbmysql.conf Archivo de configuración del módulo deAsterisk llamado CBMySQL (ConferenceBridge MySQL) usado para manejar lasconferencias en Elastix.

cdr.conf El archivo principal de configuración de lareportación de CDRs.

cdr_custom.conf Este archivo define lo que se escribe en losCDRs de Asterisk.

cdr_manager.conf Este archivo controla si se deben enviarCDRs a través del AMI (Asterisk ManagerInterface).

cdr_mysql.conf Archivo de configuración del módulocdr_mysql que permite registrar los CDRsen la base de datos MySQL.

cdr_odbc.conf Aquí se configura el módulo que permiteregistrar CDRs a través del driver ODBCde base de datos.

cdr_pgsql.conf Aquí se configura el módulo que permiteregistrar CDRs en la base de datosPostgreSQL.

cdr_tds.conf Con este archivo podemos configurar elmódulo que permite registrar CDRs a travésde los drivers de freeTDS. Por ejemplo, coneste módulo podemos registrar CDRs en labase de datos MS-SQL.

chan_dahdi.conf Este archivo contiene la configuración delos canales tipo DAHDI. Este archivotambién incluye los archivoschan_dahdi_additional.conf ydahdi-channels.conf.

chan_dahdi_additional.conf Este archivo lo sobreescribe FreePBXprincipalmente cuando se crean extensionestipo DAHDI.

cli.conf Archivo de configuración de la consola deAsterisk.

codecs.conf En este archivo se configuran algunasopciones que controlan el funcionamientode algunos codecs.

dahdi-channels.conf Este archivo se encuentra incluido en elchan_dahdi.conf y se trata de unarchivo generado automáticamente por elHardware Detector de Elastix a través de laherramienta dahdi_genconf.

dnsmgr.conf Este archivo define si Asterisk debe realizarpeticiones DNS regularmente y cada cuántotiempo.

dundi.conf Archivo de configuración de DUNDI(Distributed Universal Number Discovery).

enum.conf Archivo de configuración de ENUM.

Page 238: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

extconfig.conf Permite configurar lo que se llama“configuración externa”. Es básicamenteuna funcionalidad que permite mapearcualquier archivo de configuración con unaentidad externa como una base de datos.

extensions.ael Plan de marcado en formato AEL (AsteriskExtension Language). No se usa en Elastix.

extensions.conf Archivo de configuración que incluye aextensions_additional.conf y aextensions_custom.conf.

extensions_a2billing.conf Plan de marcado adicional para laaplicación A2Billing.

extensions_additional.conf Archivo de configuración de Asteriskmodificado por FreePBX donde no se debeeditar a mano porque los cambios seperderán.

extensions_custom.conf Archivo donde se pueden crear contextospersonalizados de Asterisk sin queFreePBX los sobre escriba.

features.conf Aquí se pueden configurar algunascaracterísticas de Asterisk como parámetrosde transferencias y captura de llamadas.

features_applicationmap_additional.conf Archivo incluido desde elfeatures.conf que contieneconfiguración de la secciónapplicationmap y que es sobrescritopor FreePBX.

features_applicationmap_custom.conf Archivo incluido desde elfeatures.conf que contieneconfiguración de la secciónapplicationmap y que puede sersobrescrito por el usuario ya que no losobrescribe FreePBX.

features_featuremap_additional.conf Archivo incluido desde elfeatures.conf que contieneconfiguración de la sección featuremapy que es sobrescrito por FreePBX.

features_featuremap_custom.conf Archivo incluido desde elfeatures.conf que contieneconfiguración de la sección featuremapy que puede ser sobrescrito por el usuarioya que no lo sobrescribe FreePBX.

features_general_additional.conf Archivo de configuración general defeatures que sobrescribe FreePBX.

features_general_custom.conf Archivo de configuración general defeatures que puede ser escrito por el usuarioya que FreePBX no lo sobrescribe.

festival.conf Archivo de configuración de Festival.followme.conf Configuración de la funcionalidad followme.func_odbc.conf Permite configurar parámetros de conexión

con una base de datos a través del driverODBC para poder hacer consultas encaliente a través del mismo plan de

Page 239: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

marcado.globals_custom.conf Permite al usuario definir variables globales

que no serán sobrescritas por FreePBX. Estearchivo es incluido desde elextensions_additional.conf.

gtalk.conf Archivo de configuración para que Asteriskfuncione como cliente del servicio GoogleTalk.

h323.conf Archivo de configuración para protocoloH.323 según la implementación basada enel proyecto Open H.323. Existen otrasimplementaciones.

http.conf Configuración de mini servidor Webembebido en Asterisk. Por omisión esteservicio está apagado así que tener cuidadode no levantarlo en el mismo puerto que elservidor Apache que viene integrado en elElastix.

iax.conf Archivo principal de IAX que incluye a losotros.

iax_additional.conf Configuración de IAX generada porFreePBX no se debe editar.

iax_custom.conf Configuración de IAX que se puede editarya que no la sobrescribe FreePBX.

iax_general_additional.conf Archivo complementario al iax.confdonde FreePBX escribe configuracióngeneral. Esto es porque en la actualidad elarchivo iax.conf ha quedado como unsimple archivo de inclusión, o sea queincluye a otros archivos.

iax_general_custom.conf Similar aliax_general_additional.confpero aquí puede escribir información elusuario ya que este archivo no essobrescrito por FreePBX.

iax_registrations_custom.conf Similar al iax_registrations.confpero este archivo no es sobrescrito porFreePBX, permitiendo almacenarconfiguración del usuario sin temor a que sesobreescriba.

iax_registrations.conf Archivo utilizado por FreePBX paraalmacenar información de cadenas deregistro con otras centrales o proveedoresVoIP que usan protocolo IAX.

iaxprov.conf Archivo utilizado par actualizar el firmwarede dispositivos IAX.

indications.conf Archivo para configurar la definición detonos. Estos tonos pueden variar de un paísa otro o de una compañía telefónica a otra.

jabber.conf Archivo que permite configurar el soporteXMPP en Asterisk. Esto es porque Asteriskse puede conectar como cliente a unservidor XMPP (El nombre Jabber es el

Page 240: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

anterior nombre del protocolo XMPP).jingle.con Archivo de configuración de Jingle. Jingle

es una extensión del protocolo XMPP quepermite soportar multimedia a través de esteprotocolo.

localprefixes.conf Archivo que permite configurar reglas demarcado basadas en prefijos.

logger.conf En este archivo se puede configurar ellogging de Asterisk. Ver la sección dediagnóstico para mayor información.

manager.conf Archivo de configuración del servicio deAsterisk Manager Interface.

manager_additional.conf Información de configuración de AMI quepuede ser sobrescrita por FreePBX.

manager_custom.conf Información de configuración de AMI parauso del usuario, o sea que este archivo no essobrescrito por FreePBX.

meetme.conf Configuración de los cuartos de conferenciapermanentes.

meetme_additional.conf Configuración de cuartos de conferenciaescrita por FreePBX.

mgcp.conf Configuración de protocolo MGCP.misdn.conf Archivo de configuración del canal

chan_misdn en Asterisk.modem.conf Archivo de configuración del soporte para

modems e ISDN usando los drivers deISDN4Linux o CAPI4Linux.

modules.conf Este archivo le dice a Asterisk cuálesmódulos se cargan y cuáles no.

musiconhold.conf Aquí se configura la música en espera.Asterisk es muy flexible e inclusive soportastreaming de audio.

musiconhold_additional.conf Archivo para configuración de música enespera que sobrescribe FreePBX.

musiconhold_custom.conf Definición de música en espera definida porel usuario. Este archivo no lo sobrescribeFreePBX.

muted.conf Permite enviar audio a ciertos canales yreducir el volumen de dicho audio mientrasestos canales están activos.

osp.conf Permite configurar soporte para protocoloOSP (Open Settlement Protocol). Esteprotocolo nos permite intercambiarinformación (como accounting y uso) conproveedores que soporten dicho protocolo.

oss.conf Permite configurar canales tipo OSS (OpenSound System). OSS es un driver de audio(o un conjunto de drivers de audio) y nospermite configurar canales en la propia detarjeta de sonido.

Page 241: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

Algo similar al soporte ALSA.parking_additional.inc Archivo que almacena cierta información

de lotes de parqueo. Este archivo se escribeautomáticamente por el módulo Parkinglot.

phone.conf Permite configurar canales tipo phone quese basan en una implementación de canalpara el proyecto Linux Telephony quesoporta este tipo de dispositivos en Linux.

phpagi.conf Configura algunos parámetros básicos parael soporte de la librería PHPAGI.

privacy.conf Básicamente este archivo define el númerode intentos que tiene un usuario paraintentar ingresar un número de teléfonoválido en la aplicaciónPrivacyManager().

queues.conf Archivo general de configuración paracolas. Si desea editar las colas en archivosde texto, se recomienda modificarqueues_custom.conf.

queues_additional.conf Archivo que crea colas generado desdeFreePBX. No se debe modificarmanualmente porque se pueden perder loscambios.

queues_custom_general.conf Archivo de configuración general de colasescrito por el usuario, es decir que no losobrescribe FreePBX.

queues_custom.conf Archivo de configuración de colas quepuede ser modificado por los usuarios sinque FreePBX lo borre.

queues_general_additional.conf Archivo de configuración general de colasescrito por FreePBX.

queues_post_custom.conf Actualmente FreePBX no usa este archivo.res_mysql.conf Permite a Asterisk obtener la configuración

de la base de datos MySQL. El concepto sedenomina Asterisk Realtime.

res_odbc.conf Permite a Asterisk obtener configuración debases de datos a través del driver ODBC.

res_pgsql.conf Permite a Asterisk obtener configuración dela base de datos PostgreSQL.

res_snmp.conf Permite configurar soporte SNMP enAsterisk.

rpt.conf Archivo de configuración de repetidora deradio. Esto le permite a Asteriskcomunicarse vía VoIP utilizando tecnologíade repetición de radio.

rtp.conf Configuración del protocolo RTP. Aquí sepuede configurar el rango de puertos RTPque Asterisk utilizará.

say.conf Define ciertos parámetros deinternacionalización.

sip.conf Archivo de configuración de SIP queincluye a los otros.

Page 242: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

sip_additional.conf Configuración de SIP generada porFreePBX y que no se debe editarmanualmente.

sip_custom.conf Configuración de SIP que se puedemodificar y no es sobre escrita porFreePBX.

sip_general_additional.conf Archivo complementario al sip.confdonde FreePBX escribe configuracióngeneral. Esto es porque en la actualidad elarchivo sip.conf ha quedado como unsimple archivo de inclusión, o sea queincluye a otros archivos.

sip_general_custom.conf Similar alsip_general_additional.confpero aquí puede escribir información elusuario ya que este archivo no essobrescrito por FreePBX.

sip_nat.conf Configuración para trabajar con SIP através de NAT (Network AddressTranslation).

sip_notify.conf Utilizado para configurar el soporte quepermite reiniciar algunos teléfonos SIPremotamente.

sip_registrations_custom.conf Similar al sip_registrations.confpero este archivo no lo sobrescribe FreePBXpermitiendo almacenar configuración delusuario sin temor a que se borre.

sip_registrations.conf Archivo utilizado por FreePBX paraalmacenar información de cadenas deregistro con otras centrales o proveedoresVoIP.

skinny.conf Permite configurar el protocolo SCCP(Skinny Client Control Protocol) enAsterisk.

sla.conf Configuración de SLAs (Shared LineAppearances).

smdi.conf Permite configurar soporte SMDI (StationMessage Desk Interface) que le permite aAsterisk funcionar como un sistema devoicemail para centrales que soportan esteprotocolo.

udptl.conf Le permite a Asterisk soportar paquetesUDPTL. Estos paquetes son utilizados porel protocolo T.38 para fax.

unicall.conf Aquí se puede configurar el módulochan_unicall.

users.conf Este archivo se utiliza para definir elconcepto de “usuario” que puede tenerasociado opcionalmente un teléfono (oextensión). Esto modela mejor el hecho deque un mismo usuario puede cambiar dedispositivo telefónico y desde cualquierdispositivo se puede autenticar.

Page 243: Comunicaciones Unificadas Con Elastix Vol. 1

Comunicaciones Unificadas con Elastix Vol. 1

http://www.elastixbook.com/es/capitulos/Apendice.htm[24/11/2011 10:23:16 p.m.]

vm_email.inc Plantilla de email que se envía paranotificar al usuario de la llegada de unnuevo correo de voz.

vm_general.inc Algunos parámetros generales relacionadoscon el voicemail.

voicemail.conf Archivo de configuración de los casillerosde voz.

vpb.conf Archivo de configuración de tarjetasVoiceTronix.

El siguiente grupo de archivos puede ser encontrado en versiones de Elastix menores a 2.0, cuando todavía seutilizaban los drivers de Zaptel. Los enlistamos aquí como referencia. Archivo Descripciónzapata_additional.conf Archivo que sobrescribe FreePBX y que se

incluye en el zapata.conf. Se utilizabásicamente cuando se crean extensionestipo ZAP.

zapata-channels.conf Archivo escrito por el scriptgenzaptelconf y por el detector dehardware de Elastix para agregarconfiguración al zapata.conf.

zapata.conf Configuración de las tarjetas de telefoníaque usan los drivers de Zaptel.

Anterior Ir a índice

Page 245: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

IndexCoverIndexIntroduction1. Introduction to telephony

1.1 A brief history of telephonyThe dawn of telephonyThe problem with the patentsThe development of telephonic technology

1.2 The basics of voice transmissionFrequency range of the human voiceThe microphoneBandwidth and information capacity

1.3 Voice digitizationNyquist's theorem

1.4 Circuit-oriented networks1.5 Packet-oriented networks1.6 Public Switched Telephone Network (PSTN)1.7 Analog circuits

Analog signalingDTMFsThe Analog Telephone

1.8 Digital circuitsBase DS-0T-carrier and E-carrier circuitsSONET optical circuits

1.9 Digital signaling protocolsChannel Associated Signaling (CAS)Common Channel Signaling (CCS)

2.Introduction to VoIP2.1 VoIP: a protocol soup

Classifying VoIP protocols2.2 IP Protocol

The InternetWhat is IP protocol?IP AddressIP packetIP routing

2.3 Transport protocolsTCP protocolUDP protocol

2.4 Voice codification

Page 246: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

Codecs2.5 Protocol overload

Comparing codecs3. Linux for Elastix Administrators

3.1 Introduction3.2 The Linux Terminal3.3 Basic Commands3.4 File System

OrganizationPermissions

3.5 RPMs and updates via YumYum to the rescue

4. Asterisk: Essential Concepts4.1 What is Asterisk?4.2 A Brief History of Asterisk4.3 Functionality Provided by Asterisk4.4 Asterisk Operation

Asterisk directoriesModular structure

4.5 The DAHDI ProjectA Brief History of DAHDI

4.6 Asterisk ConfigurationConfiguration filesComments on the Configuration Files

4.7 Dial planContextsExtensionsVariablesMost common applications

4.8 Asterisk CLICLI Commands

5. Installing Elastix5.1 Installing from a CD5.2 Installing Elastix over a soft-RAID

6. Introduction to Elastix6.1 What is Elastix?6.2 A brief history of the project

Awards6.3 Elastix features

PBXFaxEmailInstant Messaging (IM)

Page 247: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

CalendarCollaborationCall CenterGeneral

6.4 Licensing6.5 Elastix.org: Official project site

Forums6.6 The Elastix Web interface6.7 Network configuration6.8 Overview of the Elastix Web administration interface

Menus and modulesNavigating the Web interface

6.9 User administrationUser groupsGroup permissionsUser creation

7. Basic PBX Configuration7.1 Creating an extension

IP telephone configuration7.2 General configurations

Dial Options7.3 Queues configuration7.4 IVR and the recording system

Recording of the welcome messageConfiguring a welcome IVR

7.5 Conference rooms7.6 Call parking7.7 Music on Hold7.8 Operator panel7.9 Call transfer operations

Blind transferAttended transfer

8. Hardware configuration8.1 Types of cards and manufacturers8.2 Hardware installation for telephony hardware in Elastix8.3 Physical installation of a card

Modular hardware8.4 Hardware detection8.5 Telephony hardware configuration on the Asterisk level

Configuration of the chan_dahdi.conf file8.6 Digital interface configuration using the DAHDI configuration files

DAHDI driver configuration8.7 DAHDI details

Page 248: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

8.8 Before DAHDI: machines using ZaptelSome name changes to take into account

9. IP telephone configuration9.1 Softphone configuration9.2 IP telephone configuration

Network configurationConfiguration for registration on the Elastix server

9.3 Using the Endpoint ConfiguratorConfiguration of an ATCOM telephone, model AT-530Configuring a Polycom Soundpoint IP 501 telephoneTFTP updatingCustomizing configuration files

10. Advanced PBX Configuration10.1 Call routing

Incoming routesOutgoing routes

10.2 TrunksIAX and SIP type trunksDAHDI trunksCustom trunks

10.3 BillingVisualizing, Editing, and DeletingCreating a rateBilling reportDestination DistributionBilling Setup

10.4 ReportsCDR ReportChannel Usage

10.5 DISA Configuration10.6 Time conditions

11. FreePBX internal operation11.1 FreePBX basics11.2 File organization11.3 Configuration

amportal.conf11.4 retrieve_conf: Dial plan generator11.5 dialparties.agi11.6 Structure of a FreePBX module

12. Connecting Elastix Servers12.1 Interconnection between two Elastix servers

Defining the SIP trunkDefining outgoing routes

Page 249: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

12.2 Connection with call providers via IPDefining the SIP trunkDefining the outgoing route

12.3 Predefined connection with call providers via IP13. Voice quality

13.1 Voice problem symptomsEchoLow volume levelVoice delayVoice distortion

13.2 Parameters related to voice quality in packet networksNetwork delayPacket lossJitter

13.3 How to measure voice qualityMOS scaleModel E

13.4 Echo cancellersOperation of echo cancellersG.168 standardOSLEC

14. Uncovering VoIP Protocols14.1 SIP Protocol

Protocol detailsSIP signalizationAsterisk and SIP

14.2 IAX ProtocolPhases of an IAX callFrames

14.3 RTP protocolStructure of an RTP packet

14.4 SRTP Protocol15. Basic problem diagnostics

15.1 Interpreting the logThe /var/log/asterisk/full fileWhat information can the MESSAGE field give us?Process number (PID)

15.2 Diagnostics through the CLI15.3 Sniffing

16. Asterisk external control16.1 Asterisk AGI

Execution of AGI scriptsParameters sent to the AGI() script

Page 250: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Index.htm[24/11/2011 10:23:19 p.m.]

AGI commandsAGI librariesExample of a simple AGI script

16.2 Asterisk AMITesting from telnetAMI packet typesAMI actions or commands

Appendix A: Asterisk configuration files distributed with Elastix

Page 251: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Cover.htm[24/11/2011 10:23:22 p.m.]

Go to Index

Unified Communications with Elastix

Volume 1

Second edition

Edgar Landívar

Copyright (c) 2008-2011 Edgar Landívar The following work is licensed under the terms of the Creative Commons Attribution-Share

Page 252: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Cover.htm[24/11/2011 10:23:22 p.m.]

Alike 3.0 license. For a copy of the license, visit http://creativecommons.org/licenses/by-sa/3.0/;or send a letter to Creative Commons, 171 2nd Street, Suite 300, San Francisco, California,94105, USA. Second Edition

To Danielita, because of her smile...

Acknowledgment Making this book involved a huge amount of work that was made easier thanks to the generous collaboration ofsome people to whom I am enormously grateful. My most special thanks to:

• José Landívar and Alfredo Salas of ElastixDepot LLC, for their careful revision of Volume 1, paragraph byparagraph.

• To my wife, for her understanding during the time that I had to dedicate to the writing of this book.• To Paul Estrella, our Channel Manager, for exerting the necessary pressure so that this work would be

finished.• To Bob Fryer for his commited work reviewing the English version of this book.

The book online From the second edition, this book has its own website at http://www.elastixbook.com. From here, the reader willbe able to access the book in HTML format.

Where to buy this book?

Page 253: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Cover.htm[24/11/2011 10:23:22 p.m.]

You can buy the printed edition from Lulu.com and the digital version, available for Kindle readers, fromAmazon.com. A hyperlink is available at http://www.elastixbook.com.

Feedback As always, any suggestion will be well received. The reader should not hesitate in writing an email [email protected]

Go to Index

Page 254: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/Introduction.htm[24/11/2011 10:23:23 p.m.]

Go to Index

Introduction Many things have changed in Elastix since the year 2008, when this work was published for the first time. I mustadmit that I thought initially that updating the book would be an easy task, but I quickly realized that it entailed anenormous amount of work. Being immersed day by day in the development of a product, I had not noticed thegreat amount of changes that occurred since that October of 2008, when the first version was launched. The initial“easy” task took 4 times longer than planned, delaying the date of publication more than once. That first edition launched in 2008, was for me, a much bigger success than I had hoped. From the first day, myinbox was filled with many thanks and suggestions for the next versions. The book turned into an official textbookfor Elastix' training and certification and even won a sales prize at Lulu.com, something that, I must admit, was abig and welcome surprise. Despite this, the most important thing is that that first edition left me with the indescribable personal satisfaction offeeling like a writer. While I wrote it, I could not perceive this, since I was more concentrated in writing a bookthat would be useful for the Elastix user community. However, soon after its publishing, when I started to receivethe first feedback from interested readers, I knew that I had done something important, not only for Elastix users,but for myself. In regards to the changes in this second edition, I must mention that I have tried to keep the chapters in this workfaithful to the original structure to make reading easier for those that read the prior edition. However, a lot ofcontent has been updated or improved. Some chapters have been almost rewritten, while in others the retouchinghas only been superficial. I have nothing left but to invite you to explore the fascinating world of Unified Communications and of course,using Elastix. -- Edgar LandivarElastix Project Leader

Go to Index

Page 255: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.1_A_brief_history_of_telephony.htm[24/11/2011 10:23:25 p.m.]

Go to Index Next

1Introduction to telephony

I don’t care if I die, others will finish my work...-- Mark Twain

1.1 A brief history of telephony Without a doubt, the invention of what we today know as telephony must have been an amazing act in its time,almost like magic. To hear in real time the voice of someone standing at a remote spot come out of a mysteriousbox, in a time in which this was only possible in science fiction, must have been a unique and almost fantasticalexperience. Surely the idea of a talking device was already in the minds of many inventors since ancient times. However, onlyuntil the beginnings of the 19th century did it seem like something reachable, since electricity had already beendiscovered, the telegraph had been invented, and some were already experimenting with radio waves.

The dawn of telephony

In the middle of the 19th century, there was an interesting movement in what we know now as the telephone.In 1849, Antonio Meucci, Italian doctor considered by many as the inventor of the telephone, made ademonstration of a device able to transmit voice in Havana, Cuba. A few years later, in 1854, Meucci himself madea new demonstration of his invention in the city of New York, USA. While Meucci dedicated himself to the tasks of being an inventor, others were also pursuing the idea of building a“talking telegraph” and that is how in 1860 the German Johann Philipp Reis built a device capable of transmitting

Page 256: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.1_A_brief_history_of_telephony.htm[24/11/2011 10:23:25 p.m.]

voice. Charles Bourseul, who described the building of that device in 1854 but never actually built it, based thisdevice on the original idea. Reis continued improving his device and one year later, he was already transmittingvoice at a distance of more than 100 meters.

Reis' telephone

A couple of years later Innocenzo Manzetti built the long awaited “talking telegraph” that he himself hadenvisioned since 1844, but he was not interested in patenting it.

The problem with the patents Until that moment in history, there already existed some prototypes of the telephone, but no one had patented them. The first to try to patent the invention was Meucci, who in 1871 subscribed a document of “patent notice,” but dueto his economic condition was never able to pay the money to finish the procedure and his document expired a fewyears later. Meucci was never able to commercialize and cash-in on his invention. In 1875, one year after Meucci's patent expired, Alexander Graham Bell, a Scotsman living in the United States,was able to patent a similar device and was the first to do so. Bell had been previously experimenting with some ideas to conceive his telephonic device until one day he wasable to generate some sounds using electricity. History says that the first call he made was to tell his assistant thefamous phrase “Mr. Watson, come here. I want to see you.” An interesting fact that provoked some controversy was that another inventor named Elisha Gray tried to patent asimilar invention only a few hours after Bell. The two inventors entered a well-known legal dispute, which wasfinally won by Bell. Thanks to the patent, Bell was able to turn the idea of the telephone into a viable business and has the merit ofhaving developed the idea and turned into something practical for society.

Page 257: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.1_A_brief_history_of_telephony.htm[24/11/2011 10:23:25 p.m.]

Illustration of two people talking on the phone in the late 19th century

It is said that at some time or another Bell tried to sell his patent to Western Union for $100 thousand dollars butWestern Union’s president declined because he thought that the telephone was nothing more than a toy. Only twoyears later, the same director from Western Union told his colleagues that if he could get Bell's patent for $25million dollars he would consider it a bargain! This gives us an idea of how Bell's business was starting to grow in those times. In 1886, there were already morethan 150,000 telephone users in the United States. From then on, telephony started turning, little by little, into a basic service of today's society.

The development of telephonic technology As it always happens with technological advances, telephony continued to evolve. At the beginning for a user tocommunicate with another, he had to solicit a call from an operator. This operator would manually connect thecables to connect one point to the other. In 1891, the automatic telephone was invented, which allowed one to dialdirectly. At the beginning, Bell was the only company exploiting this technology, due to their patents. However, when theseexpired hundreds of little companies were born that started to sell this service, most in rural areas where Bell stilldid not reach. Little by little, these companies started to grow and at the beginning of the 20th century together,they had more users than Bell itself. Competition did its thing and telephonic technology accelerated in itsevolution. By the end of World War II, the telephone service had reached millions of users. It should be mentioned that userswould rent the telephone device from the telephone company as part of their contract. In 1947, the scientists at Bell invented the transistor and changed the course of humanity's history. In 1948, theywon the Nobel Prize for their work. In the 1960's the first communications satellites were launched and communications between continents were madeeasier. It should be mentioned that this would not have been possible without the previous invention of thetransistor. In 1982, the department of Justice of the United States won a trial against AT&T (Bell's new name) in which they

Page 258: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.1_A_brief_history_of_telephony.htm[24/11/2011 10:23:25 p.m.]

won an accord to dismantle the company into seven regional telephone companies known as Regional BellOperating Companies (RBOCs) or “Baby Bells”. All of this in exchange for the rights to enter the computermarket. After this and other legal decisions, users could buy their own telephone devices, which ended up diminishingAT&T's monopoly. The company lost a large part of its value and got into deep financial trouble. The irony is thatin 2005, AT&T ended up being acquired by one of the Baby Bells, SBC Communications.

Go to Index Next

Page 259: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.2_The_basics_of_voice_transmission.htm[24/11/2011 10:23:27 p.m.]

Previous Go to Index Next

1.2 The basics of voice transmission The human voice is composed of acoustic waves that travel through the air at the speed of sound, 1,244 km/h (or340 m/s). This is faster than a commercial plane. But this speed does not mean that you can easily communicatewith distant points since the human voice will diminish quickly, losing energy as it travels. After a few meters, wecannot listen to a conversation. The human voice is of the same nature as the rest of acoustic waves, something that was well known from beforethe invention of the telephone. Before the invention of the telephone, it was known that other types of waves called electric waves could betransmitted through a metal conductor like a copper cable. This second type of wave has a different naturecompared to acoustic waves and travels at the speed of light, or approximately 300,000 km/s. This is faster than wecan imagine and for practical purposes, we can say that these waves will travel almost instantly from one point tothe other. Another interesting aspect is that we can control how these waves diminish and make them travel greatdistances.

Since these facts were already known in the mid-19th century, it is easy to understand how many pursued the ideaof transforming acoustic waves into electric waves to be able to then transmit them great distances through metallicconductors. The problem was inventing a device to make that transformation and there was the key to the wholething. This device, known as a microphone in our days, is an important part of any telephonic device.

Frequency range of the human voice Another important feature of human voice is that the vocal chords will modulate the voice in a wide spectrum offrequencies that go from the low to high in a range of approximately 200Hz to 7kHz. A really wide range ofsounds! This makes us assume that a microphone has to be able to capture and transmit all of this range of frequencies.However, now we know that to transmit an understandable voice, it's not necessary to transmit in all thefrequencies but only in a much smaller range, which has its advantages since it makes transmission easier as we'llsee farther ahead. So commercial telephones only transmit an approximate range from 400Hz to 4kHz. This distortsthe voice somewhat although it is still possible to understand. That's why when we hear someone on the phone, hisvoice will sound slightly different from real life, but we can still understand the conversation.

The microphone The microphone was a key element in the invention of the telephone since it converts mechanical waves intoelectrical waves. Many types of microphones operate on different principles. One that was used for a long time in telephones wasmade of carbon, which consisted of a capsule filled with carbon grains between two metallic plates. One of theplates was a membrane that would vibrate with light pressure from the voice waves. In this way, the electricresistance of the capsule would change with the voice and it would generate the corresponding electrical signal.

Page 260: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.2_The_basics_of_voice_transmission.htm[24/11/2011 10:23:27 p.m.]

Carbon microphone extracted from a rotary telephone

Another kind of microphone that is very common today is the dynamic or electromagnetic microphone, whichconsists of a spool of copper wire rolled around a center made out of magnetic iron. This center is attached to adiaphragm that vibrates with the pressure of the voice waves. In this way, a light electric current is induced in thespool, which is later amplified inside the telephone.

Diagram of an electromagnetic microphone

Bandwidth and information capacity Bandwidth can be a term that is hard to understand at first since it is a very wide concept. In general, we can say that bandwidth is the measure of the amount of information that we can transmit through amedium per unit of time. Due to it being a measure of time, many times it is associated with speed. But we have tocareful with not confusing the two. A common measure to express bandwidth is bits per second. This measure can be abbreviated as bits/s, bps orbauds. Bandwidth is an important term when we talk about telephony since in real time communication there is aminimum bandwidth required to deliver communication to its destination.

Page 261: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.2_The_basics_of_voice_transmission.htm[24/11/2011 10:23:27 p.m.]

Previous Go to Index Next

Page 262: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.3_Voice_digitization.htm[24/11/2011 10:23:28 p.m.]

Previous Go to Index Next

1.3 Voice digitization Digital networks of voice and data transmission are common in our time. They were created because they havecertain advantages over analog networks; for instance, they preserve the signal almost unaltered throughout itswhole journey. That is to say, it is harder for the communication to be affected by external factors such as electricnoise. Also, it gives us methods to periodically verify the integrity of the signal, among other advantages. Simply put, digitizing a voice signal is simply taking samples (at regular time intervals) of the analog signal'samplitude and transforming this information into binary code (1s and 0s). This process is called sampling.

Nyquist's theorem In 1928 Henry Nyquist, a Swiss engineer that worked for AT&T, solved the dilemma of the minimum number ofsamples necessary to be able to rebuild a wave to its original shape. The proposed theorem reads that the sampling frequency must be at a minimum twice the highest frequency in thesignal. This is better reflected in the following expression:

fm ≥ 2 BWs Let us make a brief calculation to see what would be the sampling frequency to convert the signal of a humanvoice (analog) into digital and then being able to rebuild it at its destination. We had already said that for the human voice to be understandable it is enough to transmit in a range offrequencies between 400Hz and 4kHz. So, according to Nyquist's theorem, we should sample twice the higherfrequency as a minimum, which would be 8kHz. Further ahead, we will see that the frequency of sampling of 8,000Hz is the one that is used in most codecs. ThanksNyquist!

Previous Go to Index Next

Page 263: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.4_Circuit-oriented_networks.htm[24/11/2011 10:23:29 p.m.]

Previous Go to Index Next

1.4 Circuit-oriented networks Circuit-oriented networks (circuit switched) are those in which an exclusive or dedicated circuit is establishedbetween both nodes before the users can communicate. Once a circuit is established between two points that want to communicate, the result is the equivalent of physicallyconnecting a pair of cables from one end to the other. This circuit is exclusively reserved for one conversation andcannot be used by others. In each circuit, delay is constant, which is an advantage. However, these kinds of networks are expensive because adedicated circuit is necessary for the conversations of each individual user. This kind of networks is traditionally used today by telephone companies around the world, and is the same onethat Bell used in its beginnings, obviously considering the technological distance. It is common that certain people confuse circuit networks with analog networks, but it is necessary to make clearthat circuit networks can very well transport digital data.

Previous Go to Index Next

Page 264: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.5_Packet-oriented_networks.htm[24/11/2011 10:23:30 p.m.]

Previous Go to Index Next

1.5 Packet-oriented networks Packet-oriented networks (packet switched) are those in which different information flows are transmittedsimultaneously in the same medium. To do this, the traffic of each flow of information is divided into fragments orpackets, which are sent, interspersed. Then, at their destination, the packets are reassembled to reproduce theoriginal message.

Graphic simulation of information flow in a packet-oriented network

The Internet is an example of this type of network, where a single connection can transmit different flows ofinformation. In this same way, we can attend a videoconference while at the same time sending an email or surfingthe Web. In these types of networks, we can even have simultaneous information flowing to different IP addressesdestinations. Unlike circuit-oriented networks, in these kinds of networks bandwidth is not fixed since it depends on the networktraffic at a given time. In addition, each packet of a single flow of information is not required to follow the samepath to reach its destination. Due to this, the packets that were originally generated in sequence can reach theirdestination out of order. It is important to take these kinds of factors into account when one utilizes voice on apacket network, since they affect the quality of the call. Packet networks have become popular, mainly because they optimize resources due to being able to use the samemedium to send several flows of information.

Previous Go to Index Next

Page 265: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.6_Public_Switched_Telephone_Network.htm[24/11/2011 10:23:30 p.m.]

Previous Go to Index Next

1.6 Public Switched Telephone Network (PSTN) The public switched telephone network or PSTN is essentially a circuit-based network. This network coverslandlines as well as mobile telephones and is what makes it possible for us to communicate with any person in ourcity or around the world. Originally, it was an analog network although now it is mostly a digital network. It is important to check both kindsof circuits: analog and digital.

Previous Go to Index Next

Page 266: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.7_Analog_circuits.htm[24/11/2011 10:23:32 p.m.]

Previous Go to Index Next

1.7 Analog circuits Analog circuits are commonly copper pairs that reach users of the phone service and that transmit the electricsignal of the voice in an analog manner. The same circuit additionally carries the signaling necessary to establish,maintain and end a call. These analog circuits must connect a telephone switch charged with directing thecommunication between users. Now, analog circuits are in decline since telephone companies have found many advantages in digitalcommunications. For this reason, although today we still see some analog circuits, this is really their last mile. In acertain point of the telephone network is turned digital and transmitted to a digital telephone switch. Analog circuits are commonly associated with the term: “traditional telephony”. Since originally it was more common for phones to be located in rural areas with no electric supply, it was decidedearly on that telephone lines contain a certain voltage. That is why some analog telephones do not need to beconnected to an electric current. In any case, the Central Office (CO / Telephone Exchange) generates 48 volts of direct current to feed its users'phones. Strictly speaking, we should say -48 volts since this voltage is measured in respect to one of theconductors. However to be practical, we will use interchangeably 48V or -48V to refer to the same thing in thisbook.

Analog signaling For telephone lines to work correctly it is necessary to count with indications or electric signals that allow us tointerchange information between the user and the CO. In short, we will see what the most common signals consistof. The industry has developed three methods of analog signaling through the years. This are called loop start, groundstart and kewlstart. It’s important when configuring a telephone device that is connected to an analog line tochoose the correct method of signaling or we will find strange problems on the line like having it hang upunexpectedly, or not being able to hang it up correctly, among other things. The difference between loop start and ground start is in the way the telephone requires a dial tone from the CO (aprocess also known as seizure). Ground start requires a dial tone when it lands (hence the term ground) on one ofthe conductors of the telephone line while that loop start does so making a short circuit between both conductors(creating a loop). Kewlstart is an evolution of loop start that adds a bit more intelligence to the disconnection detection (call hangup) but is still a loop start. Due to the ground start not being very common today, we will usually find ourselves using the loop start. Below we will explain in more detail the analog signaling for the most common events. To do so we will baseourselves in the progress of a typical call using loop start signaling. The progress of a call can be divided into six

Page 267: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.7_Analog_circuits.htm[24/11/2011 10:23:32 p.m.]

instances: on-hook, pick-up, dialing, commutation, ringing and conversation.

On-hook While the telephone is hung up, the CO provides a voltage of DV 48 volts. The phone maintains an open circuitwith the telephone line; in other words, it acts as if it is not connected so current does not flow through the line.

Pick-up When the user picks up the telephone receiver, the phone sends a signal to the CO. This signal consists in closingthe circuit. The phone connects both cables of the telephone line through an electrical resistor. As soon as the CO realizes this, it sends a dial tone to the phone. This dial tone tells the user that he can then dialthe number. In most of America, the dial tone consists of two sinusoidal waves sent simultaneously. These waves are 350 Hzand 440 Hz. In Europe, the dial tone consists of a single 425 Hz wave. However, there are countries where thesevalues could be different.

Note: As a teenager, we would tune a guitar listening to the dial tone of a telephone since 440 Hz is thefrequency of the musical note A, which corresponds to the fifth string of a guitar.

Dialing Dialing can be by pulses or by tones. Pulses are almost not used anymore and were popular back in the days ofrotary phones. Tones are pairs of frequencies associated with telephone digits. These frequencies are transmitted tothe CO, which translates these tones into numbers. Further ahead, we will explain more about these tones under the title DTMF's.

Commutation Once the digits are received, the CO will try to associate the dialed number with the circuit of a user. In case thedestination is not a local user, it will send the call to another telephone switch so it can be completed. It should be said that today commutation is a completely automated process unlike the past in which it was anoperator's job.

Ringing Once the CO finds the destination user, it will try to ring him. The ring signal is a sinusoidal wave of 20 Hz and 90

Page 268: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.7_Analog_circuits.htm[24/11/2011 10:23:32 p.m.]

volts of amplitude. Note: An observant person will see that the ring signal has considerable amplitude of 90 volts. We shouldalso remember that the line already has an additional component of 48 DC volts. This is the reason why ifwe manipulated bare telephone wires in the precise moment in which it rings we may receive a smallelectric discharge and a good scare.

Apart from the ring signal the CO sends to the destination, a notification to the party who originated the call is alsosent. This audible tone is known as ring-back, which consists of two sinusoidal waves superimposed, 440 Hz and480 Hz. These waves are interspersed with periods of silence. In case the destination is in the middle of an active call then instead of the ring-back, a busy tone is returned to theoriginator of the call. This busy signal consists of two sinusoid waves superimposed, 480 Hz and 620 Hzinterspersed with periods of silence of half a second. Without a doubt, all the readers have heard about ring-back and a busy tone at some point of their lives.

Conversation If the destination decided to answer the phone call, it will close the telephone circuit (in the same way thathappened when the telephone that originated the call picked up the receiver.) This signal will tell the CO that thedestination decided to answer and will complete the connection. The telephone call is finally established.

DTMFs Many times it is necessary to send digits through the phone line to both, dial and while in the middle of aconversation. This is why DTMF’s were implemented. DTMF is an acronym for Dual-Tone Multi-Frequency. EachDTMF is really two tones that are mixed and sent simultaneously through the phone line. This is done this way todiminish errors.

The pairs of frequencies for each digit are illustrated below. 1209 Hz 1336 Hz 1477 Hz 1633 Hz697 Hz 1 2 3 A770 Hz 4 5 6 B852 Hz 7 8 9 C941 Hz * 0 # D

As you can see in the table there are also correspondences for the signs * and # as well as for the letters A, B, C,and D.

The Analog Telephone

Page 269: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.7_Analog_circuits.htm[24/11/2011 10:23:32 p.m.]

It is important to talk about this essential component of a telephonic network. Let us remember that its inventionmarked the development of the telephony business. The analog phone is still the most common kind of phone on the planet and the understanding of its operation willallow us to understand further ahead some key concepts, like echo, for example. The analog telephone, in its most basic form, is a simple device that is made up of several components. • Receiver• Microphone• Switch for hanging up and picking up• Two to four string converter (also called a hybrid)• Dialer• Bell or ringing device

Diagram of components of an analog telephone

Most components are self-explanatory. However, some readers will ask themselves about the 2 to 4 wire converter,also known as a hybrid.

2 to 4 wire converter An important part of an analog phone is the converter from 2 to 4 wires, also known as a 2H/4H device, hybrid coilor simply hybrid. This device is necessary to separate the outgoing audio signal from the incoming audio signalsince they are both part of one conversation and there is only one pair of cables. If there were three or four cables(2 outgoing and 2 incoming), the converter would not be necessary, but this would probably raise the cabling costsand telephone companies would rather deal with the coupling problems that this converter introduces instead ofraising their costs. In general, a perfect 2 to 4 wire converter does not exist since it is very hard to completely separate incoming andoutgoing signals. That is why this device is historically one of the causes of echo in badly coupled telephone lines.We will talk more about this in the chapter on Voice quality.

Previous Go to Index Next

Page 270: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.8_Digital_circuits.htm[24/11/2011 10:23:33 p.m.]

Previous Go to Index Next

1.8 Digital circuits The PSTN also provides its users with digital circuits. These circuits offer the advantage of being able to multiplexmore than one line in the same medium, which results attractive to users with a need for a great number of phonelines, usually businesses.

Base DS-0 To put it simply, DS-0 is a digital 64Kbit/s channel. A DS-0 is a standard channel measure or unit that allows us todefine greater multiples like the circuits that will be discussed below.

T-carrier and E-carrier circuits T-carrier circuits were designed as a nomenclature for multiplexed digital circuits and were developed by BellLabs more than fifty years ago. E-carrier circuits are the European equivalent. The T1 (and its counterpart, the E1) is the most popular among the T-carrier circuits. A T-1 is a digital circuitcomposed of 24 DS-0's while an E1 is composed of 32 DS-0's. If we do the math, we will realize that a T1supports 1.544 Mbit/s while an E1 supports 2.048 Mbit/s. There are higher multiples of T1, such as T2, T3 and T4, which related to each other in the following proportions:

1 T4 = 6 T3 = 42 T2 = 168 T1

SONET optical circuits SONET (Synchronous optical networking) was developed with the objective of counting with a nomenclaturesimilar to T-carriers but using fiber-optic technology. SONET uses multiples of T3 for its bandwidths and itscircuit base is the OC-1 equivalent to one T3. OC-1 has higher multiples such as OC- 3, OC-12, OC-24, and OC-48 among others.

Previous Go to Index Next

Page 271: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.9_Digital_signaling_protocols.htm[24/11/2011 10:23:33 p.m.]

Previous Go to Index Next

1.9 Digital signaling protocols Signaling protocols are used to transmit information on the state of the communications channel (such as“disconnected”, “ringing”, “answered”,) control information and digital information such as DTMFs, caller ID,among others. These protocols can be grouped into two types called Channel Associated Signaling (CAS) and Common ChannelSignaling (CCS.) The difference is in that, while CAS transmits the signaling in the same channel in which theinformation travels, CCS transmits it separately. This is why with CAS the available bandwidth is slightly reducedfor communications, since a part of it is being used for signaling. Most phone companies have adopted CCS due tothis as one of the reasons.

Note: The reader should not confuse CAS and CCS with signaling protocols. They are only types ofprotocols that are explained here to make the categorizing or grouping of them simpler.

Channel Associated Signaling (CAS) CAS protocol is better known as robbed-bit and is used by T1 and E1 circuits around the world. Robbed-bit takes (or robs, hence its name) the eighth-bit from each communications channel every six frames andreplaces it with signaling information. The original robbed bit is simply lost.

Note: As an example for the reader, each T1 frame consists of 193 bits, 8 bits for each of the 24 channelsplus 1 framing bit.

It should be noted that this is possible due to the voice not being very sensible to the loss of that bit of informationsince it is the least significant bit. However, when we transport data (as opposed to voice) the loss of one bit cannotbe overlooked and the quality of transmission will degrade in a significant manner. Another CAS type protocol that is used in our times is R2. This protocol was popular in the 1960’s. Actually, R2 isa family of protocols in which each implementation is called a variant. There are variants for each country andeven between each telephone company, which offers it.

Note: Before version 1.6, Elastix supported R2 protocol using the Unicall library (http://www.soft-switch.org/unicall/installing-mfcr2.html), but since Elastix 1.6, the support was changed so that the openR2project developed by Moisés Silva could be implemented (www.libopenr2.org).

Common Channel Signaling (CCS) The best example of CCS type protocol is the Integrated Services Digital Network (ISDN). This protocol allows us to transmit voice and data simultaneously over copper telephone pairs with a qualitysuperior to analog telephone lines.

Page 272: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_1/1.9_Digital_signaling_protocols.htm[24/11/2011 10:23:33 p.m.]

The objective of ISDN was to simplify digital connections to be able to offer a wide array of integrated services tothe users. ISDN establishes two types of interfaces to meet this end.

BRI: Basic Rate InterfacePRI: Primary Rate Interface

A BRI supposes 2 usable channels (also called B channels) of 64Kbit/s each, plus one signaling channel of16Kbit/s (also called D channel) that in total adds up to 144Kbit/s. BRI was intended to be a popular standard for homes but it did not work out this way and had a poor reception inthis market segment in the United States. In Europe, the situation was different and it is now used in manycountries of this continent. PRI is the ideal option for bigger users, like businesses or companies since it can join up more B channels. Today itis very popular and is transmitted over T-carrier and E-carrier circuits.

Previous Go to Index Next

Page 273: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.1_VoIP_a_protocol_soup.htm[24/11/2011 10:23:35 p.m.]

Previous Go to Index Next

2Introduction to VoIP

I never did anything by accident, nor did any of my inventions come by accident; they came by work-- Thomas Edison

Voice over IP or VoIP, consists in transmitting voice over the IP protocol. Said like this it can sound simple, but IP networks were mainly designed for data and many of the advantages of IPnetworks for data are a disadvantage when it comes to voice. This is because the voice is very sensitive to delaysand transmission problems, even if they are small. As such, transmitting voice over the IP protocol required many technical problems to be solved. Fortunately,technology has evolved and due to the abilities of some talented engineers, it has resulted in solutions that removethe need for us to deal with those problems inherent to IP networks that can damage voice quality. The evolution in the quality of voice communications over IP in the last years has been really surprising. Today wecan say that voice transmission on the Internet is a viable alternative within the reach of most of us.

2.1 VoIP: a protocol soup There are many protocols involved in voice transmission over IP. There already are network protocols involvedsuch as IP itself and other transport protocols such as TCP or UDP. On top of that, you have voice signalingprotocols. If this were not enough, many more signaling protocol options are available, which can make everything sound abit confusing at first.

Page 274: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.1_VoIP_a_protocol_soup.htm[24/11/2011 10:23:35 p.m.]

VoIP protocol soup

Classifying VoIP protocols To simplify things we can classify the protocols used in VoIP in three groups: signaling protocols, voice transportprotocols and IP platform protocols.

Signaling protocols VoIP signaling protocols perform functions that are similar to their counterparts in traditional telephony, such assession establishment tasks, call progress control, amongst others. These protocols are found in the session layer(layer 5) of the OSI model. There are some signaling protocols that have been developed by different manufacturers and organizations such asITU or IETF, and which are supported by Asterisk. Some of them are:

SIPIAXH.323MGCPSCCP

Among the most popular in regards to Asterisk are SIP and IAX. Further ahead in this book, we will go into more details about the SIP protocol.

Voice transport protocols

Page 275: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.1_VoIP_a_protocol_soup.htm[24/11/2011 10:23:35 p.m.]

We should not confuse voice transport protocols with low-level transport protocols such as TCP and UDP. Herewe are referring to the protocol that transports the voice as such or what is commonly known as the packet. Thisprotocol is called RTP (Real-time Transport Protocol) and its function is simple: to transport the voice with aslittle delay as possible. This protocol starts to function once the signaling protocol has established the call between the participants.

IP platform protocols In this category, we will group protocols from basic to IP networks, which form the basis of the addition of othervoice protocols. Among these protocols, we can mention Ethernet, IP, TCP and UDP.

Note: In the present chapter, we will emphasize the explanation of this group of protocols so we can bringup to speed those without solid knowledge in Networking. However, the other protocol groups will beexamined in more detail in a chapter that is specially dedicated to this purpose.

Protocols involved in a SIP call. The case of IAX is very similar.

In the above figure, we can observe a curious fact in that although SIP supports both UDP and TCP we can onlysee it on top of UDP. This is not a mistake but it is because until Asterisk 1.4 the SIP implementation is onlyavailable for UDP. Starting in Asterisk 1.6 (Elastix 2.0) SIP is available on TCP as well as on UDP.

Previous Go to Index Next

Page 276: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.2_IP_Protocol.htm[24/11/2011 10:23:37 p.m.]

Previous Go to Index Next

2.2 IP Protocol IP protocol is without a doubt one of the most popular ever implemented, mainly because of the great network ofnetworks called the Internet that uses this protocol for its routing. For this reason, before we go into detail about IPprotocol we will use a pair of paragraphs to summarize the origins of the Internet.

The Internet The internet had its origins in the 1960's as a project created by the Department of Defense of the United Stateswith the goal of creating a robust network that could connect some public sector facilities with universities. Theidea behind this network, originally called ARPANet, was that if any of the nodes stopped working this would notsignificantly impair the operation of the network. For this a decentralized network was created that could handlemore than one route between two points. In short, it was about building a fail-proof network (let us remember thiswas during the Cold War) that was also low-cost.Thanks to this goal, ARPANet evolved into what we know today as the Internet, such a big and powerfulcommunications network that has made an impact in our cultures without a doubt. Without its existence, theElastix project would never have existed and you would not be reading this now.

What is IP protocol? IP protocol (Internet Protocol) works at a network level where information is sent in packets called IP packets.This protocol offers a service without guarantee, also known as a best effort service. That is, nothing guaranteesthat the packets will reach their destination, although the best effort will be made to have them arrive.

IP Address An IP address is a unique number, which also gives information on the location of the machine that has it. Toensure the uniqueness of this number, an authority controls the assigning of IP addresses called IANA (InternetAssigned Numbers Authority.) This unique number is binary and has 32 bits. This number is shown as four decimal number separated by periodsfor practical considerations and for easy understanding by humans. Each of the four decimal numbers can have avalue from 0 to 255. An example of an IP address is 172.16.254.1

Translation from decimal notation to binary (32 bits) of an IP address

IP packet

Page 277: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.2_IP_Protocol.htm[24/11/2011 10:23:37 p.m.]

As we said before, IP protocol is the protocol that divides information into packets, which are sent to itsdestination. The advantage of having information in packets is that each of these packets can take a different routeto reach its destination. That is, there is a redundancy in the number of routes and it is less likely for packets to belost. Some readers will ask themselves: What do these so-called packets look like? The format of an IP packet is designed to carry information that allows it to be dissected to its destination andobviously to be reassembled with other packets at the destination to recover useful information. The figure belowrepresents an IP packet header.

IP packet header

IP routing Routing allows the optimal route to be determined so that an IP packet reaches its destination. To know where asingle packet wants to go, we have to examine the IP address of the destination in the Destination Address field inthe heading of an IP packet. The devices in charge of routing the packets to their destinations are known as routers. They contain routing tableswith information on how to reach other networks. That is, when a packet reaches a router, the router examines theIP address of the destination and tries to determine what network this IP address belongs to. Determining the network where a single packet wants to go is not hard because that information is part of the IPaddress. That is because each IP address can be divided into two parts: the part that identifies the network andanother one that identifies the device (also known as the host.) Identifying each of these parts is not a trivial matter since there exist networks of different sizes and the number ofbits that correspond to the network and the host vary respectively. The solution to this is an additional parameterknown as the network mask.

Network mask and network address calculation Let us see then how to obtain the information of to what network does a device belongs to based on its IP addressso that a router can correctly send a packet to that destination. The network mask is a 32-bit number like the IP address. It is called a mask because if it is superimposed over the

Page 278: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.2_IP_Protocol.htm[24/11/2011 10:23:37 p.m.]

IP address it allows us to identify which part corresponds to the network address and which one corresponds to thehost address. Let us imagine that we have the IP address 130.5.5.26 with a mask of 255.255.255.0. To show how the mask isapplied to the IP address we will turn this data into binary as is shown in the diagram below.

Mask application to obtain the network and host information

Now we can see more clearly that the number one (1) in the mask marks the limit between the network part and thehost, so the network address is (in binary):

10000010.00000101.00000101.00000000 All the binary numbers to the right of the network part in the mask are filled with zeros. Let us now turn the abovenetwork address into decimal. We will get:

10000010.00000101.00000101.00000000 130.5.5.0 This implies that the IP address 130.5.5.26 belongs to the network 130.5.5.0.Now the router can decide to which network to send our IP packet.

Previous Go to Index Next

Page 279: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.3_Transport_protocols.htm[24/11/2011 10:23:38 p.m.]

Previous Go to Index Next

2.3 Transport protocols

Note: We should not confuse these protocols with “voice transport protocols” RTP. RTP is a morespecialized protocol that even can be mounted on UDP (A protocol that will be explained here). Thetransport protocols covered here are for general purposes and rest directly on top of the IP protocol.

TCP protocol As we had said, the IP protocol does not guarantee that data will reach its destination. It only makes the best effortto ensure that it will arrive. Due to this best effort, a protocol was needed to be responsible for the data transmission. The Transmission ControlProtocol or simply TCP was designed for this reason. This transport protocol is transmitted on top of the IPprotocol. TCP helps by making sure that the transmitted data is free of errors and is received by the applications in the sameorder it was sent. If data is lost in the way, TCP introduces a mechanism so that this data can be resent. Obviously, this implies an extra load of information on the data flow since there is additional control information tobe sent. That is why TCP is a good protocol for session control but not so good for real-time informationtransmissions like voice. However, TCP plays an important role in many protocols related to the Elastix server. TCP introduces the concept of a port that is nothing else but an abstraction to be able to relate data flows withspecific network services (or higher-level protocols). For example, port 80 is associated with the Web service orHTTP protocol, while port 25 is associated with email service or SMTP protocol.

UDP protocol UDP (User Datagram Protocol) is another transport protocol. It is different from TCP, as this protocol does notcare if the data arrives with or without errors and does not care if it arrives in sequence. The question is then, whereand why is this protocol used? Well, a transport protocol does not necessarily have to guarantee that the information reaches its destiny or that itarrives in sequence. This is just an extra feature. It is somewhat like a merchandise transport service. Let usimagine a fleet of motorcycles that offers transport services in a city and let us imagine that that fleet is hired fortransporting a great shipment of files from one office to the other. The company will be in charge of dividing ourshipment of files and distributing it into quantities or packets that can be transported in each vehicle. The fleet willdo whatever it needs to make sure the shipment reaches its destination. This is in essence what a transport servicedoes. However, we can choose two kinds of services: one that guarantees that the merchandise arrives safely andone that does not. These two services are analogous to the two kinds of transport protocols that we are describinghere: UDP and TCP. In the end, UDP divides the data into packets, also called datagrams, to be transported inside the IP packets to itsdestination.

Page 280: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.3_Transport_protocols.htm[24/11/2011 10:23:38 p.m.]

Since it is not necessary to include too much control information, the UDP protocol reduces the quantity ofinformation necessary in the packets, which makes it a faster protocol than TCP. This makes it suitable for thetransmission of information that must be sent in real time, such as voice. This is why VoIP voice applications are transmitted with this protocol.

Previous Go to Index Next

Page 281: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.4_Voice_codification.htm[24/11/2011 10:23:38 p.m.]

Previous Go to Index Next

2.4 Voice codification It is clear that to transport voice there are some protocols used such as SIP, IAX and others such as RTP or RTCP.But voice is an analog wave that needs to be transformed into a digital format before being transmitted. Logically we could try to transmit it just as it results from an analog to digital conversion (ADC) but we are in apacket network so we need to packetize this information. There also exists the possibility of compressing the resultof ADC conversion with an algorithm so not to waste network resources. The search for an optimal compression format generated some alternative transmission formats called codecs.

Note: Codecs are not really exclusive of VoIP since they are also used in other kinds of digitalcommunications.

Codecs The word codec comes from abbreviating the words codification and decodification. Its main purpose is to adaptthe digital information of the voice to obtain some benefit. This benefit in many cases is the compression of thevoice in such a way that we can use less bandwidth than was necessary. Some of the codecs supported by Asterisk and commonly used in VoIP communications are G.711, G.722, G.729,GSM, and iLBC among others. Let us briefly look at four of them: G.711, G.722, G.729 and GSM.

G.711 G.711 is one of the most used codecs of all time and comes from ITU-T standard that was released in 1972. Itcomes in two varieties called u-law and a-law. The first version is used in the United States and the second is usedin Europe. One of its characteristics is its voice quality since it hardly compresses it. It uses an 8 bit - 8kHz sampling, resultingin 64kbit/s. It is the recommended codec for LAN networks, but you should think twice about using it for remotelinks due to the large amount of bandwidth that it consumes. The support for this codec is a default setting in Elastix.

G.722 G.722 offers a sampling rate of 14 bits at 16 kHz, much higher than G.711. In other words, it recovers more datafrom the audio signal, which results in a superior voice quality. In fact, the codec is used in many VoIP telephonesmarked as high definition (HD.)

Page 282: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.4_Voice_codification.htm[24/11/2011 10:23:38 p.m.]

Something very interesting about G.722 is that despite having a sampling rate that is higher than G.711's and thefact that the resolution of each sample is also higher than G711, the bandwidth consumed is almost the same,64kbit/s. This is possible due to G.722 codec using a different algorithm. If we look quickly at the human voice bandwidth that this codec can capture (according to Nyquist's theorem seenin the last chapter), we will see that the sampling rate of 16kHz allows us to digitize frequencies of up to 8kHz.That is, twice the bandwidth of G.711, including high frequencies. These high frequencies contain high tones thatmake the voice clearer and more understandable. With the recent arrival in the market of phones that claim to have High Definition Audio (HD), we have seen anincrease in the use of this codec. The reader may think that this is a new technology; however, G.722 is a 1988standard.

G.729 This is also an ITU recommendation whose implementation has been historically licensed. This means that usuallyyou have to pay for them. The advantage in using G.729 lies mainly in its high compression and the resulting low consumption of bandwidth.This makes it attractive for Internet communications. Despite its high compression, G.729 does not deterioratevoice quality significantly and for this it reason has been widely used over the years by many manufacturers ofVoIP products. G.729 uses 8kbit/s on each channel. If we compare this to the value in G.711 (64kbit/s) we'll see that it consumes 8times less bandwidth, which at a glance if a significant saver of our resources.

Note: There exists a variation of G.729 that use 6.4kbit/s and 11.8kbit/s. To use G.729 channels in Elastix a license must be acquired for each channel.

GSM Many people correctly assume that the GSM codec has something to do with cell phone communication standards.The standard that defines cell-phone technology GSM (Global System for Mobile communications) includes thiscodec. The advantage of this codec is also its compression. However, the voice quality is deteriorated compared to othercodecs. You will notice this when you talk through a GSM cell phone at some point. GSM compresses approximately at 13kbit/s and comes ready to be used by default in Elastix.

Previous Go to Index Next

Page 283: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.5_Protocol_overload.htm[24/11/2011 10:23:40 p.m.]

Previous Go to Index Next

2.5 Protocol overload By what we have seen above, transporting voice from one place to the other in a packet network requires the helpof some protocols. In addition, we have noticed that these protocols transmit additional data that uses up bandwidthapart from the actual voice. Some of them are Ethernet, IP, UDP, and RTP. All this makes the real bandwidthrequired to transmit voice to be higher than the actual codec. For example, to transmit voice using G.711, in theory we should be using 64Kbps (according to the codec) when inreality we are using 95.2Kbps of bandwidth. In other codecs with more compression, the overload is even moresignificant (percentage-wise.) Let us do a simple exercise using as an example the G.711 codec. Let us see the following figure to illustrate theexercise better:

Illustration of protocol overcharge using G.711

Let us calculate the bandwidth for G.711 basing ourselves in the above figure, which shows us the waste oroverhead of each protocol. Let us add up all of these sent bytes. Bytes transmitted for each 20ms of audio = 38 + 20 + 8 + 12 + 160 = 238 bytes Bits transmitted for each 20ms of audio = 238 bytes * 8 bits/byte = 1904 bits Bits transmitted each second = 1904 bits/20ms * 1000 ms/sec. = 95,200 bits/s = 95.2Kbps!

Comparing codecs Below we show a table that shows the overhead for some of the most popular codecs supported by Asterisk.

Page 284: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_2/2.5_Protocol_overload.htm[24/11/2011 10:23:40 p.m.]

Codec Codec Bandwidth Real Ethernet Bandwidth Overhead PercentageG.711 64 Kbps 95.2 Kbps 48.75%iLBC 15.2 Kbps 46.4 Kbps 205.26%G.729A 8 Kbps 39.2 Kbps 390%

Previous Go to Index Next

Page 285: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.1_Introduction.htm[24/11/2011 10:23:40 p.m.]

Previous Go to Index Next

3Linux for Elastix Administrators

Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest ofthe world mirror it

-- Linus Torvalds, Linux creator

3.1 Introduction This chapter will review some useful Linux concepts, which will make work easier for Elastix administrators. Ifyou already know how to manage Elastix from the Linux terminal, you can skip this chapter and go straight to thenext. Since this is not a Linux manual, we will not go too deeply into the subject or talk about the history of Linux or itsadvantages. When Reading this chapter, if you think we are looking at the topic too broadly, that is the intention Even though this chapter is a good start for the reader with no Linux experience, we recommend learning toadminister it since that will, without a doubt, make tasks easier as an Elastix administrator.

Previous Go to Index Next

Page 286: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.2_The_Linux_Terminal.htm[24/11/2011 10:23:42 p.m.]

Previous Go to Index Next

3.2 The Linux Terminal A very comfortable way to administer Elastix is from the Linux terminal. The Linux terminal allows us to get themost out of our server of unified communications We can enter the terminal directly by connecting a monitor and a keyboard to the machine in which Elastix isinstalled. Alternately, we can connect remotely though the SSH protocol. If we are on a Windows machine, we will need to download a client so we can connect remotely. The program werecommend is named PuTTY. Do a Google search for its name you will find the download site. Just make sure todo so from the official site.

PuTTY application

After entering the parameters of the Elastix server and starting our session, we can execute commands as if wewere directly connected with a monitor and keyboard.

Page 287: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.2_The_Linux_Terminal.htm[24/11/2011 10:23:42 p.m.]

Running PuTTY

Previous Go to Index Next

Page 288: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.3_Basic_Commands.htm[24/11/2011 10:23:44 p.m.]

Previous Go to Index Next

3.3 Basic Commands The most commonly used basic commands in Linux are listed below. Command Descriptionls Lists the files in the current directoryls -la Lists the files and their attributescd <directory> Changes directorycd .. Changes to the home directorycat <file> Shows the contents of a file onscreenpwd Shows the route to the current directorycp <file1> <file2> Copies a file or a group of filesmv <file1> <file2> Moves a file. Is also used to rename filesrm <file> Deletes a filetail -f <file> Shows the last lines of a file dynamicallymkdir <directory> Creates a directorytar -xvzf <file>.tar.gz Decompresses a tar.gz filetop Shows a real-time report of the processes

running on the system. Can be ordered bymemory consumption or CPU. Very usefulfor diagnostics.

find <directory> -name <file> Allows you to search for files in a particulardirectory

vim <file> Program for editing files in plain textifconfig Shows information on the different network

interfaces and allows them to be modifiedtemporarily.

ps -aux Shows a report of the processes that arebeing run on the server.

reboot Reboots the machineshutdown -h now Shuts the machine down

Page 289: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.3_Basic_Commands.htm[24/11/2011 10:23:44 p.m.]

Example of the “top” command

Previous Go to Index Next

Page 290: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.4_File_System.htm[24/11/2011 10:23:45 p.m.]

Previous Go to Index Next

3.4 File System In Linux the organization of the file, system is very important. This organization gives Linux its resilience and interoperability since programs can better predict exactly wherecertain files are for them to work correctly. Also, it allows processes to write files in a way that other componentswill understand. This minimizes conflicts and, along with a permission system, it makes the operating system moresecure.

Organization The directory organization that we will see below is not arbitrary. It is the product of years of evolution from thefirst versions of UNIX until reaching what we know today as Linux. This folder structure is found in what is called the root directory, or main directory. This root directory is thehighest-level directory in the file system and is represented with a slash “/”. The directories listed in the followingtable are all on the root directory Directory Descriptionsbin Includes binaries that can only be executed

by an administratorbin Contains binaries necessary for the correct

functioning of the system. The binaries inthis folder can also be used by the system’susers

boot Contains the kernel and other filesnecessary for startup

dev Includes files that represent hardwaredevices. Let’s remember that in Linuxpractically everything is a file

etc Basically contains configuration files for thewhole system

home Here are the user directories. For example,/home/Jorge/ is the directory for the usernamed Jorge

lib Contains the shared libraries required byprograms. It’s somewhat analogous to the.dll files in Windows

lost+found If for some reason the file system iscorrupted and needs to be repaired, theresults of this repair are saved in thisdirectory

mnt This is a common place for mounting otherfile systems or devices. For example, a CD-ROM drive or a USB drive

Page 291: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.4_File_System.htm[24/11/2011 10:23:45 p.m.]

opt Contains software packages that arenormally not part of the original installation

proc This is a virtual directory (since it actuallyresides in the memory) where the kerneland drivers write files so that otherprograms can read them. For example, hereis where the DAHDI drivers write certainfiles in the path /proc/dahdi

root Contains files for the user root since thisdoesn’t have a path of the /home/root type

tmp Saves temporary filesusr Is one of the most important directories and

contains information to be shared withsystem users. That is, here are the programsalong with the necessary documentation andeven the related libraries. Usually, thisdirectory doesn’t contain data that changesconstantly

var Contains data that is constantly changing,like logs or email tails. For example, here iswhere the Asterisk log resides, in the path/var/log/asterisk/full

Permissions In Linux, each directory or file has access permits, these permits can be of 3 types:

ReadingWritingExecuting

The permissions can be applied to the file’s owner, to a group of users of the system, or globally to all of thesystem’s users. For each of these entities there can be established different permissions. With that said, we can establish the following matrix for permissions that would be valid for any one file in thesystem: owner group Other usersReading x x xWriting x Executing x x x

In the above example, the owner has all of the permissions on the file while the group and global users only havepermissions for reading and executing. There is an easier notation to express this information. This notation is composed of 10 characters that simplify thedisplay of permissions information and allows showing them in a single line. This is very useful when you want tosee the permissions on a group of files, although it takes time to get used to it. For example, the permissions matrixfrom the above example can be expressed in the following way (we have included the position of each permission

Page 292: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.4_File_System.htm[24/11/2011 10:23:45 p.m.]

with a number from 0 to 9):

-rwxr-xr-x0123456789

Where,

The character in the 0 position represents the kind of file. If it has a letter “d”, that means that this is adirectory.The characters in the 1, 2 and 3 positions represent the reading, writing and executing permissions for thefile’s owner.The characters in the 4, 5, and 6 positions represent the reading, writing and executing permissions for thefile’s group.The characters in the 7, 8, and 9 positions represent the permissions for reading, writing and execution for allusers.

Now let us see an example of a listing where we can appreciate different permissions: $ ls -ladrwxrwxr-x 4 edgar edgar 4096 2008-09-01 21:20 Codigo-rw-rw-r-- 1 edgar edgar 53058 2008-08-04 01:31 comohemo.mid-rw-rw-r-- 1 edgar edgar 22785270 2008-08-07 12:09 dlj173.pdfdrwxrwxr-x 3 root root 4096 2008-08-26 17:21 elastixdrwxrwxr-x 2 test prueba 4096 2008-09-11 13:03 flashingfopdrwxrwxr-x 3 edgar edgar 4096 2008-08-04 22:18 fpbx-rw-rw-r-- 1 edgar edgar 398439 2008-08-19 19:19 gforge_manual.pdf-rwxrw-r-- 1 edgar edgar 102135 2008-09-07 18:53 index2.html-rw-rw-r-- 1 user4 101 3535 2008-08-19 23:20 install-cerosdrwxrwxr-x 3 edgar edgar 4096 2008-08-03 01:52 installers-rw-rw-r-- 1 edgar edgar 6860 2008-08-19 23:12 ksraid.cfgdrwxr-xr-x 4 edgar edgar 4096 2008-08-06 12:14 lw-rw-rw-r-- 1 edgar edgar 1020152 2008-07-30 14:00 Magic Button.pdfdrwxrwxr-x 3 edgar edgar 4096 2008-09-02 17:25 monitoring-rw-rw-r-- 1 edgar edgar 14341913 2008-08-12 01:59 prbx1.zip-rw-rw-r-- 1 edgar edgar 7195354 2008-08-03 01:51 rotron1.7.1.tar.bz2-rw-rw-r-- 1 edgar edgar 25343 2008-08-13 00:25 roundcube.diff-rw-rw-r-- 1 edgar edgar 12167 2008-08-01 23:03 src-php.tar.bz2drwxr-xr-x 18 edgar edgar 4096 2008-08-13 09:38 wanpipe-3.2.7-rw-rw-r-- 1 edgar edgar 16106184 2008-08-29 17:40 wanpipe-3.2.7.1.tgz-rw-rw-r-- 1 edgar edgar 20525 2008-09-08 17:14 xorcom_test.txt-rw-rw-r-- 1 edgar edgar 9277 2008-09-08 02:10 Xorcom_logo.png

Examples of file permissions

Numeric representation of permissions Apparently, we will complicate things a bit more here, but later on we will see the usefulness of being able torepresent the permissions matrix in a more condensed form called a numerical or octal permissions representation. The idea is that the three characters that define the permissions for each one of the three entities involved (owner,group and others) can be represented by a single number. In this way, all the permissions information for a file canbe represented with three of these numbers. For example, 755. Where the first digit represents the owner’spermissions, the second digit the group’s permissions and the third digit the permissions for other users or globalpermissions

Page 293: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.4_File_System.htm[24/11/2011 10:23:45 p.m.]

At first, it can be hard to understand but, without a doubt, it is a more condensed format. Let us see the nextexample: -rwxr-xr-x is equivalent to 755 Each of the three characters that represent a permission for an entity can be replaced by a 1 or a 0 in such a waythat we get a binary number. This number is translated to its decimal equivalent (we really should say octal here) aswe see below: -rwxr-xr-x Transformed to binary, it would be made up of the following trios (without taking into account the 0 position thatcorresponds to the directory): 111 101 101 And now its decimal equivalent:

755 For those that do not like to calculate in binary, perhaps the following table will be useful: Text version Binary version Octal version--- 000 0--x 001 1-w- 010 2-wx 011 3r-- 100 4r-x 101 5rw- 110 6rwx 111 7

Now you are probably wondering, what is this numerical notation for? Well, this way it is much easier to manipulate the permissions for files with commands, which is precisely what wewill see below:

Changing file permissions and owner The permissions and owner changing tasks can be executed easily thanks to the commands chmod and chownrespectively. chmod takes as parameters the permissions in a numerical mode and the name of the file which you want tochange. For example: $ ls -la test_file

Page 294: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.4_File_System.htm[24/11/2011 10:23:45 p.m.]

-rw-rw-r-- 1 edgar edgar 0 2008-09-19 04:21 test_file$ chmod 755 test_file$ ls -la test_file-rwxr-xr-x 1 edgar edgar 0 2008-09-19 04:22 test_file

The chmod command can also be used recursively to change the permissions for all of the files in a folder. This isdone with the R option. For example: chmod –R 755 folder_name/ To change the owner and group associated with a specific file we can use the chown command. For example, tochange the permissions for the above file to the user and root group we execute the following (note the separationbetween user and group by a period “.”): # ls -la test_file-rwxr-xr-x 1 edgar edgar 0 2008-09-19 04:23 test_file# chown root.root test_file# ls -la test_file-rwxr-xr-x 1 root root 0 2008-09-19 04:24 test_file

As with the chmod command, the chown command also supports the recursive option with R.

Previous Go to Index Next

Page 295: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.5_RPMs_and_updates_via_Yum.htm[24/11/2011 10:23:46 p.m.]

Previous Go to Index Next

3.5 RPMs and updates via Yum The software packages that are included in Elastix come in a format called RPM. This is a format inherited fromRed Hat and its name means Red Hat Package Manager. This means that the installers of many additional softwarepackages can be installed in Elastix in an easy way using compressed packages usually with the .rpm extension. RPMs also allow us to update software packages and they solve the necessary dependencies so that these packagesdo not problems in the system. This can be done because the RPM system maintains an internal database of all theinstalled packages with their respective dependencies and versions. It also gives us a very useful command tomanipulate installs, uninstalls, upgrades, and other important tasks. Below are some common options for the rpm command: Action CommandRPM installation rpm -ivh <package>.rpm

RPM upgrade rpm -Uvh <package>.rpm

Deletes an RPM rpm -e <package>.rpm

Gets information from an RPM file rpm –qpi <package>.rpm

Obtains a listing of all installed RPMfiles on the system

rpm -qa

Yum to the rescue Manual installation of RPMs with the rpm command is fine for many tasks. However, there are times wheninstalling RPMs in this way is tedious and complicated. For example, we install complex packages that have manydependencies. At the moment of installation, we will notice that we are required to install another package havingto search on the Internet for it. Many times an RPM has dozens or even hundreds of dependencies that, of course, would take us hours to manuallysolve. Apart from this dependencies problem there is another problem, their reliability. That is, after hours on end ofinstalling our packages manually we realize that one of them overwrote an important system file and corrupted ourElastix server. What a headache! The solution is a utility named yum. This program allows us to install RPM packets from repositories and does it ina very user-friendly way. Most of the popular distributions, and Elastix is not the exception, maintain repositories of official softwarepackages that can be accessed free on the Internet. They make their best effort so that these packages do not havedependency problems with one another. Also, the packages from the official repositories are tested to avoidincompatibility as much as possible. It is for this reason that if Elastix is used, it is advisable to install the packagesfrom the official repository.

Page 296: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_3/3.5_RPMs_and_updates_via_Yum.htm[24/11/2011 10:23:46 p.m.]

Below are the some useful yum commands: Command Descriptionyum update Upgrades the whole systemyum update <package> Upgrades only the specified package and all

its dependencies.yum install <package> Installs the specified package and all of its

dependencies

Note: It should be mentioned that Elastix gives us a user-friendly Web interface to upgrade packages andadminister repositories. That means that the manual upgrade procedures here described are saved forexceptional cases. It is recommended to use the Web interface whenever possible.

Previous Go to Index Next

Page 297: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.1_What_is_Asterisk.htm[24/11/2011 10:23:47 p.m.]

Previous Go to Index Next

4Asterisk: Essential Concepts

If at first, the idea is not absurd, then there is no hope for it-- Albert Einstein

4.1 What is Asterisk? Asterisk is telephone exchange (PBX) software with VoIP capability that is distributed with free licensing. Parting from this very basic concept, Asterisk is not just any PBX; it is a PBX rich in features that before wereonly accessible by purchasing expensive products. This has resulted in many businesses considering Asterisk as a serious option when planning their telephone projectand, for this reason; Asterisk has been very well received around the world. Seeing this business opportunity, many manufacturers have started to offer telephone hardware that is compatiblewith Asterisk, mostly electronic cards for PSTN connection. This has caused Asterisk-based PBX’s offerings torapidly grow in recent times. Asterisk is one of the most important components in Elastix and it provides most of the distribution’s telephonefeatures.

Previous Go to Index Next

Page 298: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.2_A_Brief_History_of_Asterisk.htm[24/11/2011 10:23:47 p.m.]

Previous Go to Index Next

4.2 A Brief History of Asterisk Asterisk was conceived and developed by Mark Spencer. At first, it was because of a personal need, since heneeded a PBX for the small support business he was founding, “Linux Support Services.” At first, he thought about acquiring a PBX but he soon realized that it was far too much for his budget. So, aftersome thought, he decided to create his own and started to code what we now know as Asterisk. In 1999, when hehad a functioning program, he decided to make it free under a GPL license. One may not think it, but Mark was no newcomer to the world of open-source software. He had alreadyparticipated actively in the development of the messaging client Gaim, now known as Pidgin, one of the mostpopular pieces of open-source software. In 2002, Linux Support Services turned into Digium, which today offers Asterisk-related products and services andhandles the development of this software. We should point out that right at the beginning Mark realized that his software needed to interact with telephonehardware. That is when he discovered the Zaptel project, an open-source project created by Jim Dixon. Zaptel hadthe aim of creating open drivers for computer telephone cards. From then on, Asterisk and Zaptel would walk handin hand to the point where today both services are maintained by Digium. In 2008, Digium decided to rename theproject they maintained with Zaptel to DAHDI.

Previous Go to Index Next

Page 299: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.3_Functionality_Provided_by_Asterisk.htm[24/11/2011 10:23:48 p.m.]

Previous Go to Index Next

4.3 Functionality Provided by Asterisk As we have said before, Asterisk is a PBX software that is rich in features. While writing this book, the mostrelevant supported features are listed below:

Automatic call answeringCall transferenceDo not disturb optionCall parkingCall pickupCall monitoring and recordingVoicemailConferencingCall reportingWaiting linesCall waitingCaller IDCaller ID blockingOutgoing and incoming faxInteractive extensions directory listingInteractive voice response (IVR)Music on HoldBehavior management by scheduleFollow me

Automatic call answering Asterisk provides the ease in configuring an automatic answering service that helps manage the flow of incomingcalls by answering them automatically with no need for a live operator. This feature has been designed forbusinesses that receive a high call flow and that do not possess the necessary staff to manage the traffic ofincoming calls. The answering service responds to the digits that are entered into the number pad by the person calling, sending thecalls to specific extensions, providing access to pre-recorded information and can take messages 24 hours per day.

Call transfer There are two methods in Asterisk to transfer calls: attended transfer and blind transfer. In attended transfer theperson at the destination is called first to notify him that a call will be transferred to him. In blind transfer, the callis simply transferred without previously speaking with the person at the destination.

Do not disturb option

Page 300: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.3_Functionality_Provided_by_Asterisk.htm[24/11/2011 10:23:48 p.m.]

This option allows the user to configure the extension so that it will not receive calls for a period. Any incomingcalls to that extension will be automatically rerouted to that same extension’s voice mail.

Call parking Call parking allows the user that receives a call to send it to a parking space, so he can take it again from anotherextension. This kind of action is useful in many situations, like when a technician receives a call at his desk thatrequires him to be in front of a server that is three stories above. In this case, the option is to send the call to avirtual room or parking space where the caller will listen to the configured music on hold. The technician canretake the call once he arrives at the server.

Call pickup This option allows one to take a call that is ringing at an extension that is not one’s own.

Call monitoring and recording Asterisk allows the monitoring and recording of calls. Monitoring is usually used in quality control for telephoneoperators and sales agents. For this, there is the feature in which by typing in a predetermined code, one is able tolisten in on a conversation taking place on any one extension. Additionally, it allows the recording of conversations from any extension randomly or previously programmed.These recordings will be stored in the Asterisk server’s hard drive for later revision.

Voicemail Voicemail is an application that allows messages left by callers that were not answered to be stored and listened to. To access the voicemail inbox you must enter a predetermined password. Asterisk will ask for the password andthen you will have access to the available messages.

Conferencing A conference is nothing more than a phone call in which several participants can speak at the same time. To accessthis feature, conference rooms are created. Each room is associated with a number, as if it were an extension. Then,to access a conference all you have to do is dial the corresponding number for that conference room. It is possible to configure some interesting settings for a determined conference room, for example limiting thenumber of speakers, asking for a password, and moderating the conference room.

Call reporting

Page 301: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.3_Functionality_Provided_by_Asterisk.htm[24/11/2011 10:23:48 p.m.]

Asterisk generates Call Detail Records (CDRs) and can store them in a database. By accessing this database,reports can be generated that detail what numbers are dialed by each extension, whether a call was answered ornot, how long the call lasted, or through what port or phone line the call was made

Queues This feature allows a great number of callers to stay on hold until a representative or resource is available to assistthem. This ensures that callers will not go automatically to voicemail, which can ensure that a caller always has theopportunity of being assisted by a person. The time the user stays on hold can be used to let him know of thecompany’s services or products, special offers, informative messages or there can simply be music on hold.

Call waiting This feature allows the person that receives a call while being on another call to temporarily interrupt the currentconversation to answer the incoming call. To alert that person that a second call is coming in, there is acharacteristic sound. In some scenarios this sound is not desirable, for example in telephone connections for datatransfer (i.e. fax.) In these cases, you can choose to turn this feature off, since it creates fax transmission errors.

Caller ID This signal is sent in between ring signals, or during the call establishment process, before it is answered. Asterisktakes advantage of this and completely supports its use at an IP extensions level. However, at the level of publiccommutated phone networks, the provider must turn on or provide this feature.

Caller ID blocking This feature prevents someone with caller ID to see the number from which you are calling. This caller ID hidingfeature can be total or selective. Not all public telephone networks support this feature. In Asterisk, this feature also includes blocking an incoming call according to the ID.

Incoming and outgoing fax Asterisk allows automatic detection of when a caller is trying to send a fax. As a part of the welcome message forthe PBX, you can add a phrase that says, “If you want to send a fax, send it now.” This allows us to eliminatepaper, to do without machines or telephone ports exclusively dedicated to fax and to digitize the informationreceived as fax. After being digitized, this document can be emailed to a specific account for review.

Interactive listing of the extensions directory Asterisk has the telephone directory for all of the company staff (first name, last name, and extension) in itsdatabase. This feature allows the person calling to enter the first four letters of the first or last name of the personwith whom he wants to speak. This can give callers an alternative if they do not know the extension of the personthey are trying to reach and only know their first or last name.

Interactive voice response (IVR)

Page 302: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.3_Functionality_Provided_by_Asterisk.htm[24/11/2011 10:23:48 p.m.]

Through this feature, access is provided to telephonic options that improve the way a telephone system receivesand distributes calls. With an IVR menu, it is possible to distribute incoming calls in a precise way. This will helpraise employee performance and customer satisfaction, since it speeds up access to the services and data possessedby the company. With this feature, automatic processes can be put into place that in certain cases can even allowworking without a receptionist. With the use of this feature, you can create number or voice command activatedmenus to even look up data in other computer systems or databases.

Music on hold Asterisk allows the use of any mp3 or wav file as background music. This will be played when an internal orexternal caller is waiting to be attended by a representative of the company. These files can even be grouped bycategories to produce different melodies for different caller groups.

Behavior management by schedule It is possible to configure Asterisk so that it will have a different treatment for calls (both incoming and outgoing)depending on the time of day, day of the month, or month of the year. The most basic example is when you wantthe incoming calls received outside of office hours to receive a message suggesting them to call again the next day.

Follow me This feature, allows to predefine a sequence of simultaneous or sequenced calls to locate a user. For example, youcould define that when the company manager’s extension rings and is not answered the call should be rerouted tohis cell phone and other contact numbers. You can specify grace periods before the next number is dialed.

Previous Go to Index Next

Page 303: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.4_Asterisk_Operation.htm[24/11/2011 10:23:49 p.m.]

Previous Go to Index Next

4.4 Asterisk Operation

Asterisk directories Asterisk organizes its files by distributing them among several directories. The most important of these are thefollowing: Directory Description/etc/asterisk/ Where the Asterisk configuration files

reside/usr/lib/asterisk/modules/ Contains Asterisk’s modules/usr/sbin/ Includes Asterisk’s binary/var/lib/asterisk/agi-bin/ Where the AGI scripts reside/var/lib/asterisk/mohmp3 Contains the Music On Hold mp3 files/var/lib/asterisk/sounds Includes the sounds that Asterisk uses as

voice prompts/var/spool/asterisk/ Where Asterisk saves the files generated by

its operation, such as voicemails and callrecordings

/var/run/ Saves files with process information (PIDs)/var/log/asterisk/ Where the Asterisk log files reside, such as

CDRs or /var/log/asterisk/full

Modular structure Asterisk uses the idea of modules to extend its functionality. The functionality residing in the modules is soimportant that without them Asterisk alone would not perform any interesting functions. These modules are in the folder /usr/lib/asterisk/modules/ and are files with the .so extension Modules can be controlled through the configuration file /etc/asterisk/modules.conf. This file tellsAsterisk whether to load a specific module through the directives load and noload. By default in Elastix, allmodules try to load. The following is a fragment of the file modules.conf that comes by default with Elastix. Here you can observehow it tells Asterisk not to load some modules during startup. ;; DON'T load the chan_modem.so, as they are obsolete in * 1.2 noload => chan_modem.sonoload => chan_modem_aopen.sonoload => chan_modem_bestdata.so

Page 304: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.4_Asterisk_Operation.htm[24/11/2011 10:23:49 p.m.]

noload => chan_modem_i4l.so ; Ensure that format_* modules are loaded before res_musiconhold;load => format_ogg_vorbis.soload => format_wav.soload => format_pcm.soload => format_au.so

Additionally, you can load modules in real time through the Asterisk console (not to confuse this with the Linuxterminal) with the command: module load <module> Further ahead we will see some more about the Asterisk console or CLI.

Previous Go to Index Next

Page 305: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.5_The_DAHDI_Project.htm[24/11/2011 10:23:50 p.m.]

Previous Go to Index Next

4.5 The DAHDI Project Even though it is a great piece of software, Asterisk cannot do all the work by itself. One of the software packagesthat complement it is called DAHDI. DAHDI is a group of drivers to control telephonic hardware like PCI or PCI Express cards, which allow us toconnect to the PSTN. These drivers communicate with Asterisk through an Asterisk module called chan_dahdi.so that is configuredthrough the configuration file /etc/asterisk/chan_dahdi.conf. Additionally DAHDI has its own configuration files, independent from Asterisk, which are found in the folder/etc/dahdi/.

Note: In versions of Elastix before 1.5, the software from project Zaptel is used instead of DAHDI. Thismeans that the configuration files for the telephony drivers have different names. In these cases, it isrecommended, as reference, to consult the first edition of this book.

Simplified diagram of the interaction between Asterisk and DAHDI

A Brief History of DAHDI Regardless of the name change from Zaptel to DAHDI and all the confusion that this generated at the beginning,we cannot forget that DAHDI’s origin was in the Zaptel project. First, because the people working on the originalproject deserve their due credit, second because we should not forget history. Following is a brief summary of thathistory.

Page 306: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.5_The_DAHDI_Project.htm[24/11/2011 10:23:50 p.m.]

In the year 2000, Jim Dixon started project Zaptel, whose name was an abbreviation of the Zapata TelephonyProject. He named it in honor of Emiliano Zapata, hero of the Mexican revolution. The drivers were launched witha GPL license so that anyone could have access to the code. Initially Zaptel had the drivers for the Tormenta (Spanish word for Storm) cards, made by Zapata Telephony. It wasnot long before Digium started to improve the drivers and extended support for new hardware models, among themthose manufactured by Digium itself. That is how Digium became Zaptel’s main developer. After a few years of maintaining Zaptel, Digium realized that Zaptel was a registered brand by a card sellingcompany and to avoid any future confusion, decided to change the name of its drivers. The name chosen wasDAHDI, which is an acronym for Digium Asterisk Hardware Device Interface. Digium ended official Zaptel support after Asterisk version 1.6

Previous Go to Index Next

Page 307: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.6_Asterisk_Configuration.htm[24/11/2011 10:23:51 p.m.]

Previous Go to Index Next

4.6 Asterisk Configuration

Configuration files Asterisk can be configured through some configuration files found on the path /etc/asterisk. There aredozens of configuration files in this directory and they are in plain text to make their modification easier. Due tothis, we can use the vim editor or the command line editor of our preference to edit them. Even though all files are important, not all of them are necessary. Elastix has already preconfigured some of themto prevent further modification. The most important are explained in the following table: File Descriptionextensions.conf Defines the dialing plan. In Elastix, there

are other files to better organize the dialingplan. These additional files start with theterm extensions_

sip.conf Configures SIP devicesiax.conf Configures IAX deviceschan_dahdi.conf Defines configuration for DAHDI-type

channels

Comments on the Configuration Files Asterisk configuration files can contain comments. A comment starts with a semicolon. Once this character iswritten, the rest of the line turns into a comment. That is, this line is ignored by Asterisk when reading the file. Letus see an example of a comment. ;; The following is a comment block.; As you can see, I can write anything; in here because it will be ignored by Asterisk.; Comments are very useful for writing; notes and information relative to the configuration; we are writing. ; Now I will continue with the directives. . .; #include sip_general_custom.conf#include sip_nat.conf#include sip_registrations_custom.conf#include sip_registrations.conf

Previous Go to Index Next

Page 308: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.7_Dial_plan.htm[24/11/2011 10:23:52 p.m.]

Previous Go to Index Next

4.7 Dial plan The dial plan in Elastix is mainly in the file extensions.conf. From this, one there are other important filesincluded which also contain portions of the dial plan. The most important are:

extensions_additional.conf: Here is where the variable plan written for FreePBX resides, animportant component of Elastix. If changes are made manually to this file, these changes will be lost whenthey are overwritten by FreePBX.

extensions_custom.conf: Here the user can manually define a dial plan. This file is not touched byFreePBX so it is safe to edit it without fear of losing any changes.

All of the dial plan files are in plain text in a format defined by Asterisk. The content of these files is divided intosections called contexts.

Contexts Contexts group the logic of the dial plan. Contexts also can include other context with the clause “include” orredirect the flow of execution of the dial plan to other contexts depending on the conditions. For example, afterexamining the prefix of the dialed telephone number, a context can contain the necessary logic to route the call tothe corresponding main line. A context can group the logic necessary for the application of an alarm clock. It canalso include the logic to have access to voicemail or to authenticate a PIN number. In general, practically the wholedial plan is grouped into contexts. Contexts are the groupers and organizers of the dial plan. Each context must have a unique name and this name is between the symbols “[“ and “]”. You can observe twocontexts called app-pickup and ext-test in the example below: [app-pickup]include => app-pickup-customexten => _**.,1,Noop(Attempt to Pickup ${EXTEN:2})exten => _**.,n,Pickup(${EXTEN:2}) [ext-test]include => ext-test-customexten => 7777,1,Goto(from-pstn,s,1)exten => 666,1,Goto(ext-fax,in_fax,1)exten => h,1,Macro(hangupcall,)

Fragment of the file extensions_additional.conf to illustrate contexts.

Reserved contexts There are two context names that are reserved for a special purpose which are [general] and [globals].

Page 309: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.7_Dial_plan.htm[24/11/2011 10:23:52 p.m.]

Extensions Contexts contain instructions, known as extensions. These extensions are lines from the dial plan that have thefollowing syntax: exten => extension_name, priority, application

Note: We usually associate the word extension with phone numbers, but in Asterisk, the term extension goesbeyond what we normally know. An extension is a logic series of the dial plan. What’s more, when we dial anumber from our telephone it does not necessarily have to ring another telephone since we can create thelogic we want for that given number. For example, we can simply make the call hang up, to reproduce agiven message or functions that are more complex.

A typical extension looks like the following: exten => 4567,1,Answer()

Extension name The extension name is a numeric identifier for the extension. Let us call it telephone number for now to simplifythe matter. There is a special non-numerical extension called extension s, to which we will give special attention. Extension s means any extension. The letter s comes from the word start. An example of the use of extension s isthe following: [test]exten => s,1,Answer()exten => s,2,noOp(“Test”)

Extension s is used when the user that made the call has not pressed the extension number. For example, this is thecase for an incoming call still listening to the IVR welcome.

Priority Priority indicates the order in which an extension is executed inside a context. It is necessary to name the firstpriority 1 so that when Asterisk reads a context the first thing it looks for is this priority. There also exists a special priority, which is priority n. Priority n means that the priority of the previous instructionis added to one. This is very useful for making easier the writing of the dial plan. For example, let us check the following dial plan:

Page 310: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.7_Dial_plan.htm[24/11/2011 10:23:52 p.m.]

exten => s,1,NoOp(“Hello, this is just an example”)exten => s,2,NoOp(“to demonstrate”)exten => s,3,NoOp(“how to use priority n”)

This dial plan could be written in the following manner using priority n: exten => s,1,NoOp(“Hello, this is just an example”)exten => s,n,NoOp(“to demonstrate”)exten => s,n,NoOp(“how to use priority n”)

Priorities can also contain tags to make their identifying easier since if we always use priority “n” it will bedifficult to access a determined location determined inside the context. This can be done with the syntaxn(tag_name).

Application It is in applications where the real power resides of the Asterisk dial plan. To make an analogy, the applications arethe equivalent to the functions in a programming language. The applications will allow us to answer or hang up acall, play waiting music, and jump to other contexts, among many other functions. Applications can also receive parameters. For example, the application Dial( ) needs you to indicate which numberto dial so that it can do its work. Further ahead in the present article, we will explain in detail the most common applications in the dial plan.

Variables Variables in the dial plan are a similar concept to variables in the a programming language. That is, they areabstractions that can store information of a variable nature. A variable has the following syntax: ${NAME} Here NAME is the name of the variable. Variables can be of three kinds: Global, Channel, and Predefined.

Global They are the variables defined in the [globals] section of the file /etc/asterisk/extensions.conf.The word global means that they can be referenced from anywhere.

Channel They are the variables that can be defined using the command (or application) Set( ).

Predefined Asterisk administrates some variable names on its own. These names are predefined and contain certain

Page 311: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.7_Dial_plan.htm[24/11/2011 10:23:52 p.m.]

information depending on the behavior of the call and other factors. Some predefined variables are: ${CALLERID(all)}${CALLERID(name)}${CALLERID(num)}${CHANNEL}${CONTEXT}${EPOCH}${EXTEN}${SIPUSERAGENT}${UNIQUEID}

Note: There is an additional kind of variable introduced in Asterisk 1.6 called a shared variable. Thisvariable allows two or more channels to have access to what would otherwise be a channel variable.

Below we reproduce a segment of the file extensions.conf that is distributed by default with Elastix. Here wecan see some predefined variables like ${UNIQUEID}, ${BLINDTRANSFER} and ${EPOCH}, and channelvariables like ${CALLFILENAME}. [macro-record-enable]exten => s,1,GotoIf($[${LEN(${BLINDTRANSFER})} > 0]?2:4)exten => s,2,ResetCDR(w)exten => s,3,StopMonitor()exten => s,4,AGI(recordingcheck,${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)},${UNIQUEID})exten => s,5,Noop(No recording needed)exten => s,999,MixMonitor(${CALLFILENAME}.wav)

Most common applications

Answer Syntax: Answer([delay]) Answers a channel immediately if it’s ringing. It can optionally receive a delay parameter that tells Asterisk that itmust wait a determined number of milliseconds after answering the call to go to the next application.

Background Syntax: Background(filename1[&filename2...][|options[|langoverride][|context]]) Plays a list of audio files in the background and returns control to Asterisk, which can continue to execute the dialplan while the audio is played. When it’s done playing the last file, it’s execution ends so if you want it to keepwaiting for an extension you should use the application WaitExten() with it. This application is typically used to reproduce the welcome message of an IVR. The Background application can receive some options:

Page 312: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.7_Dial_plan.htm[24/11/2011 10:23:52 p.m.]

Option Descriptions Skip the audio playing if the channel isn’t answeredn Don’t answer the channel before playing the filesm Stop playing audio if a dialed digit coincides with an existing extension in

the destination context.

Playback Syntax: Playback(filename1[&filename2...][,options]) Plays one or more audio files. The difference with the Background application is that Playback plays the whole fileuntil the end and does not return control until it finished playing.

Note: It is not necessary to specify the audio file’s extension in this function. The audio files are searchedfor in the directory /var/lib/asterisk/sounds

Hang-up Syntax: Hang-up() Hangs up the channel and returns the -1 value.

Goto Syntax: Goto([[context|]extension|]priority) Skips the execution of the dial plan and goes to a defined context, extension and priority. If there is only oneparameter, it is understood that it is a priority inside the same context.

Dial Syntax: Dial(type/identifier, timeout, options, URL) This command is responsible for dialing a specified channel and links it to the current channel.

Previous Go to Index Next

Page 313: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.8_Asterisk_CLI.htm[24/11/2011 10:23:53 p.m.]

Previous Go to Index Next

4.8 Asterisk CLI Asterisk CLI is the name for the Asterisk console. That is, the command line interface to control Asterisk directly. To enter the CLI we must execute the following command from the Linux terminal: # asterisk -rAsterisk 1.6.2.16.1, Copyright (C) 1999 - 2010 Digium, Inc. and others.Created by Mark Spencer <[email protected]>Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.This is free software, with components licensed under the GNU General PublicLicense version 2 and other licenses; you are welcome to redistribute it undercertain conditions. Type 'core show license' for details.=========================================================================Connected to Asterisk 1.6.2.16.1 currently running on elastix (pid = 17080)Verbosity is at least 3elastix*CLI>

As we can see, we get a CLI> prompt from which we can execute a series of commands that we will go intobriefly. CLI can also give us real time information about Asterisk’s activity. In addition, we can control the degree of detailwith which we want to see that information with some commands. The most used ones are the following: elastix*CLI> core set debug 9Core debug was 3 and is now 9elastix*CLI> core set verbose 9Verbosity is at least 9

The higher the levels of the variables debug and verbose, the more detailed the displayed information. Bydefault, the level of debug is 0 and for verbose it is 3 in Elastix.

Note: Due to the great deal of information that can be generated with these commands, it is important toreestablish the values for the debug and verbose variables their minimum when we are done with ourdiagnostic tasks. Otherwise, Asterisk will continue to generate this detailed information when we do notreally need it, which is extra work that consumes system resources. In systems with a lot of activity, thisadditional consumption can be significant and can affect the quality of the calls.

CLI Commands Below we provide a brief list of the most common CLI commands. A complete command list can be found inAppendix B. Command Descriptionagi set debug on Allows the debug of AGI scripts. It’s turned

off with “agi set debug off”core set debug channel Allows debug in a specific channel

Page 314: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.8_Asterisk_CLI.htm[24/11/2011 10:23:53 p.m.]

core set debug Allows changing of the debugging level.It’s turned with “core set debugoff”

core set verbose Raises the intensity of logging. Very usefulin diagnostic.

core show channels Shows updated information in activechannels.

dialplan reload Reloads the whole dial plandialplan show Shows the dial planhelp Shows a listing of all available CLI

commandsiax2 set debug Starts debug at the IAX level. Is turned off

with the command “iax2 set debugoff”

iax2 show peers Shows the defined peers and someadditional information like the IP addressfrom which they’re connecting, amongother data.

iax2 show registry Shows information from the IAX registryand other information like the status and IPaddress to which you are connecting.

module reload Reloads all Asterisk modules. Is useful toapply changes made to the configurationfiles.

pri set debug on Starts debug of the PRI interface spans. Itturned off with “pri set debug off”

core restart gracefully Reboots Asterisk in an ordered manner.That is, it doesn’t allow new calls to startand it waits for existing call to end beforeproceeding with the restart.

core restart now Reboots Asterisk immediatelycore restart when convenient Restarts Asterisk when there is no activity

in the Central. Adequate for productionenvironments in which we have no otheroption but to restart central but don’t wantto cut existing calls short.

sip set debug ip Sets SIP debug at the level of a specific IPaddress

sip set debug peer Sets SIP debug at the level of a specificpeer

sip show peers Shows a list of all configured SIP peers andinformation for each one, like their status.

sip show registry Shows a list with the SIP registry andrelevant information for each one.

core stop gracefully Stops Asterisk in an ordered manner. Thatis, it does not allow new calls and it waitsfor existing calls to end before stoppingAsterisk.

core stop now Stops Asterisk immediatelycore stop when convenient Stops asterisk when there is no activity in

the central. It is adequate for production

Page 315: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_4/4.8_Asterisk_CLI.htm[24/11/2011 10:23:53 p.m.]

environments in which we have no otheroption but to turn off central but do notwant to cut existing calls short.

dahdi show status Shows a listing of DAHDI channels and areport of alarms and errors

dahdi show channels Shows a listing of DAHDI channels andsome operating parameters

elastix*CLI> dahdi show channels Chan Extension Context Language MOH Interpret pseudo default default 1 from-pstn default 2 from-pstn default 3 from-pstn default 4 from-pstn default 5 from-pstn default 6 from-pstn default 7 from-pstn default 8 from-pstn defaultelastix*CLI>

DAHDI channel listing, result of the command dahdi show channels

Previous Go to Index Next

Page 316: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Previous Go to Index Next

5Installing Elastix

There are men who struggle for a day, and they are good. There are others who struggle for a year, and they arebetter. There are some who struggle many years, and they are better still. But there are those who struggle all their

lives, and these are the indispensible ones. -- Bertolt Bretch

5.1 Installing from a CD Before beginning, make sure you have a copy of the latest stable version of Elastix (the present work is based onversion 2.0.) This can be downloaded from the download page of the Elastix Project at www.elastix.org. Choosethe appropriate version depending on whether your machine has a 32 or a 64-bit processor.

Loading from CD Elastix is distributed as an ISO image file, which can be burned to a CD with any CD recording software. Once this image is burned on the CD, insert it into your drive and turn your computer on. Make sure that yourcomputer starts up from the CD-ROM drive otherwise, you need to set this option from the BIOS. If everythinggoes alright, you should get a screen like this one:

Page 317: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Initial installation screen

Note: The Elastix installation CD will format ALL of the hard drive during the installation process so makesure that you do not have any data that you will need on your hard drive.

The installation process will start automatically after ten seconds. You can press the Enter key if you do not wish towait that long.

Preferences and welcome After loading some programs necessary for the installation, the process will ask us to enter the language for theinstallation. Choose the language using the arrow keys on your keyboard. Using TAB, move the cursor on OK andpress the Enter key.

Language selection for the installation

After that, go on to choose your keyboard type according to its layout. If your keyboard’s layout is from the UnitedStates, select the “us” option.

Page 318: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Keyboard-type selection

Hard disk partitions The following is the critical step in the installation since it will configure the hard drive partitions. If you are anexperienced administrator, you can choose “Use a custom design.” Otherwise, choose “Remove all partitions onselected drives and create default layout.” In this example, we will select the latter option.

Hard drive partitioning

Partitioning Confirmation

Page 319: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Now the installation process will ask us if we want to review and modify the partitioning layout. Select the Nooption and press the Enter key to continue.

Review/Modify partitioning layout

Network parameter configuration Now it is time for the network parameter configuration. The installation program will ask if you wish to configurethese parameters in the network cards of your server. Select Yes.

Network configuration

For each network card installed, it will ask if you wish to activate it during startup and which IP support you willactivate in it. The IP protocol we recommend you choose support for is IPv4. Press OK.

Page 320: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Parameter activation on the network card eth0

If you have a Dynamic Host Configuration Protocol (DHCP) server in your network for the dynamic assigning ofIP addresses, select the option Dynamic IP configuration. Otherwise, you will have to assign an IP addressmanually selecting the option Manual TCP/IP configuration.

IP address configuration and network mask

The next screen will ask us to enter additional network parameters such as the gateway, primary DNS andsecondary DNS.

Gateway and DNS configuration

Now we need to name our server with a hostname. It must be taken into account that a correct host name has the

Page 321: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

form name.domain. Your network administrator will know what host name to use. If you do not have one, enter afake name since later it is possible to change it. Choose OK to continue.

Hostname configuration

Time zone, root password and packages In the next screen choose the time zone for your region and press OK to continue.

Time zone selection

We are now going to enter a series of high-level passwords for your Elastix system. It is strongly recommendedthat you clearly note down each password, especially as you should be using complex passwords. Do not take thissuggestion lightly as even seasoned installers of Elastix have had to re-install Elastix because they failed to writethese important passwords down. It is time to specify the root password that will be used to access the linux prompt via the console or SSH.Remember that this password is a critical part of the system’s security. Due to the importance of this step, you haveto confirm the password by entering it again. Press OK to continue with the installation.

Page 322: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Specifying the administrator password (root)

Formatting and file copying From here, the installer program will partition and format the server’s hard drive and all the data stored previouslyon the hard drive will be lost forever. In addition, all of the files necessary to run Elastix will be copied onto the hard drive.

File copying to the hard drive

Once the package copying to the hard drive is finished, the server will restart automatically. At this point, theserver will eject the CD, please remove it. If you don’t it will try to boot off of the CD and not the hard drive wherewe now want to boot from.

Automatic restart and various passwords Let the system start up by itself while making sure not to press any keys at the next screen.

Page 323: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

Elastix startup screen

After loading the programs needed for its operation, Elastix will ask you for passwords for the importantcomponents that make up your system. This password entry phase will only happen on the first startup afterinstallation. The first password that it asks for is for the MySQL database administrator. Enter a password and continue with theOK button.

MySQL administration password

You will have to confirm the password previously entered for MySQL administration in the next screen.

Page 324: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

MySQL administration password confirmation

The next password will be used to enter with administrator privileges into the Elastix graphic interface. In addition,the same password will be used to enter the FreePBX, VTiger and A2Biliing system components. Once thepassword is entered, advance to the next screen by pressing OK.

Elastix password and its components

As in the last case, you will need to confirm the password previously entered for Elastix and its components. Afterentering it once more, press OK to continue.

Confirming the password for Elastix and its components

Page 325: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.1_Installing_from_a_CD.htm[24/11/2011 10:23:59 p.m.]

.

Ending the installation The installation process will end when you get an invitation screen to enter the main server console, like is shownin the following figure:

Authentication for entering the Elastix console

To access the Elastix console, simply enter root at the pbx login prompt. The password is the one you chose duringthe installation process.

Previous Go to Index Next

Page 326: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.2_Installing_Elastix_over_a_soft-RAID.htm[24/11/2011 10:24:02 p.m.]

Previous Go to Index Next

5.2 Installing Elastix over a soft-RAID A useful configuration that Elastix has inherited from Linux is the possibility of adding resilience against hard discerrors with RAID (redundant discs). Doing this allows us to add a minimum level of redundancy at a low cost. In general, it is common to configure RAID level 1 or mirror which allows us to have data duplicated in thepartitions of various hard drives. The Linux operating system allows Elastix to additionally support RAID levels 0and 5. It is important to insist that it is not strictly necessary for all partitions to be included in this arrangement.However, it has recommended that if there are two hard drives, that a mirror is made of each partition. A typical partitioning scheme in a server without RAID consists in a 100MB partition for /boot, a 2GB partition forswap memory and the rest of the disc space in a partition for the root /. If you follow this scheme, but with a RAIDarrangement at level 1, you will need to create the three mentioned partitions in both hard drives. In this way, in theend you will have six partitions. RAID configuration through software (there is hardware that also implements RAID) is implemented during theElastix installation process. In the Partitioning types menu we must choose the option to Create a custom layout.Here is where you will have the opportunity to create RAID-type partitions and then the RAID devices that groupthese partitions. To begin the Elastix installation with RAID with software, let us start the Elastix installation in the usual way.

Initial installation screen

Just as in the normal installation process, you will have to choose a language for the installation process and thetype of keyboard according to your location.

Hard disk partitions Soon the installer program will show a screen asking for the type of partitioning that you will be doing.

Page 327: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.2_Installing_Elastix_over_a_soft-RAID.htm[24/11/2011 10:24:02 p.m.]

Partition type options.

Here you must choose the option Create a custom layout and ensure that both hard drives in the server are readyand selected. The partitioning screen will show a listing of hard drives with the partitions that are being created.

The tool shows hard drives that are yet to be partitioned

The first step will be to create all the RAID-type partitions for which you choose the option New.

Creating a RAID partition

In the next screen, you will fill out the following parameters:

Page 328: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.2_Installing_Elastix_over_a_soft-RAID.htm[24/11/2011 10:24:02 p.m.]

- Mount Point: It does not matter what you choose here, it will be removed when you select RAID software inthe next point.

- File System type: Choose RAID software- Allowable Drives: Choose a disk at a time (selecting it with the space bar).- Size: Specify the space in the disk drive that is reserved for this partition.- Force to be a primary partition: Do not select this.

Create three partitions in each one of the drives. For the size write 100 for the partition that will be assigned to the/boot directory and the double of the RAM our system has for the partition that will be assigned to the swap-typepartition (in this example our system had 500MB of RAM so we wrote 1000). For the partition that will beassigned to the root directory ( / ) write 1 and select the option Fill all available space. This will make the partitiontake up the remaining space on the hard drive.

After creating the six partitions (three in each hard drive), you will see a list as shown below. For our example, wehave used a 5GB hard disk so that the only difference should be the size of the last partition.

RAID partitions with software

In the above figure, you can see how the partitioning is exactly the same in both hard disks.

RAID Devices The following step is the creation of the actual RAID devices. For that, you choose the RAID option.

RAID arrangement creation

Now we need to create the RAID devices that will be associated to the partitions in each disk that will bereplicated. For this, we need to create three devices by accessing the Create a RAID device screen and filling in the

Page 329: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_5/5.2_Installing_Elastix_over_a_soft-RAID.htm[24/11/2011 10:24:02 p.m.]

parameters in the following way:

- Mount Point: Write /boot for the first RAID device, don’t write anything for the second RAID device (sinceit will be a swap type) and write / for the third device.

- File System type: Select ext3 for the first RAID device, swap for the second device and ext3 for the last.- RAID Level: Select RAID1 for the three devices.- RAID Members: Choose the partition pairs that have been created in each one of the hard disks respectively.

These partitions will replicate one another. In our case we have chosen hda1 from the first hard disk withhb1 from the second hard disk for the RAID device that will be mounted as /boot. In the same way we havepaired hda2 with hba2 for the swap device and hda3 and hdb3 for the / device.

- Number of spares?: This parameter is applicable in cases in which there are more than two hard disks. In ourcase, we only have two disks so the value 0 is the only option.

- Format partition?: This field must be selected. Once the three RAID devices are created, the partition list will look very similar to the one shown in the followingfigure:

Final partitioning of software RAID level 1

Select the OK option to continue with the normal installation process.

Previous Go to Index Next

Page 330: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.1_What_is_Elastix.htm[24/11/2011 10:24:04 p.m.]

Previous Go to Index Next

6Introduction to Elastix

The person who says it cannot be done should not interrupt the person doing it.-- Chinese Proverb

The idea behind this chapter is to do a quick overview of Elastix, trying to clear up some basic concepts before wego into more advanced topics. As the reader will notice, this is not a very technical chapter; rather it is informativeon a general level.

6.1 What is Elastix? Elastix is an open source distribution of a Unified Communications Server that integrates different communicationstechnologies in a single package, such as:

PBXFaxEmailInstant Messaging (IM)CalendarCollaboration

When we say distribution (or distro), we are referring to a group of software packages that are distributed together,in this case on a CD, including the installer and operating system. Once the distribution CD is installed, we willhave a Unified Communications Server ready for production. Elastix implements a great deal of its operation on four very important programs, which are Asterisk, Hylafax,

Page 331: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.1_What_is_Elastix.htm[24/11/2011 10:24:04 p.m.]

Postfix and Openfire. These programs respectively give the PBX, Fax, Email and Instant Messaging functionality.The operating system is based on the popular Linux server-focused distro called CentOS. The different Elastix components and their relationship to each other can be observed in the following figure:

General schematic of Elastix components

Previous Go to Index Next

Page 332: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.2_A_brief_history_of_the_project.htm[24/11/2011 10:24:04 p.m.]

Previous Go to Index Next

6.2 A brief history of the project Elastix was created and maintained today by the Ecuadorian company PaloSanto Solutions. Elastix was released asfree software for the first time in March of 2006. Initially it was not a distro but an interface to show Call DetailRecords (CDR) for Asterisk. It was towards the end of December 2006 when it was launched as a distro, whichcontained many diverse administrative tools under the same Web interface, and from this point forward, it startedgaining attention because of its usability. Since then, Elastix has not stop growing in popularity, having reached its first million downloads in 2010.

Awards In 2007, the project was nominated in 2 categories for the SourceForge Community Choice Awards (CCA) and wasnominated again in 2008 and 2009. In February of 2011 it received the award for best Product of 2010 given out bythe media company TMC, which also publishes the magazine Internet Telephony.

Previous Go to Index Next

Page 333: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.3_Elastix_features.htm[24/11/2011 10:24:05 p.m.]

Previous Go to Index Next

6.3 Elastix features It’s difficult to list all of the features in Elastix because new ones are constantly added. However, the mostoutstanding, based in Elastix 2.0, are the following:

PBX

Voicemail via Web or emailCall recordingComplete and highly flexible IVRCall parkingCall QueueingVoice synthesis supportCaller IDBusiness hours schedulingAutomatic provision of phones via webExtensions batch creationSupport for video via H.263 and H.264Automatic detection of telephony hardwareEmbedded DHCP serverCall detail records (CDRs)Billing with reporting of calls by destinationChannel usage report by technology (SIP, ZAP, IAX, Local, H323)Supports SIP, IAX, H323, MGCP, iLBC, protocols, among othersSupports ADPCM, G.711 (A-Law & μ-Law), G.722, G.723.1 (pass through), G.726, G.729, GSM, iLBC,codecs, among others.Supports analog interfaces FXS/FXOSupports digital interfaces E1/T1/J1 (PRI/BRI/R2)Supports mainline groupsFollow-me, ring groups, paging, DISA, Callback, Security PINs, among others.

Fax

Fax server that can be administered from the WebIntegrated Fax viewer with PDF downloadsFax-to-email implementationFax sending via WebAccess control for fax clientsIntegration capacity with Winprint Hylafax to allow printing-to-fax from Windows.

Page 334: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.3_Elastix_features.htm[24/11/2011 10:24:05 p.m.]

Email

Multi-domain Email server that can be administered from the WebOutgoing SMTP supportRelay email configurationWeb-based Email clientQuota support in email accountsDistribution list functionality via Mailman

Instant Messaging (IM)

Instant Messaging server based on integrated OpenFire ServerCalls via PBX to connected IM usersCompletely Web-based configurationSimultaneous interconnection to Yahoo, MSN Messenger, Gtalk, ICQ, and others.Server-to-server connection support for user sharingUser sessions reportPlugin supportLDAP support

Calendar

Calendar interface via WebVoice remindersEvent invitations sending via emailCalendar exporting to iCalendar format

Collaboration

Phone book with click-to-call capacityCRM functionality integrated via vTigerCRMAudio teleconferencing support configurable via WebWeb conferencing functionality via Addons

Call Center

Agent support with logon/logoffPredictive dialingGeneric forms for data entryDetailed reports by agent

Page 335: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.3_Elastix_features.htm[24/11/2011 10:24:05 p.m.]

General

Embedded online helpWeb interface with multi-language supportSystem visualization via DashboardDate/Time/Time Zone configurationNetwork parameter configurationUser and permissions configurationBackup configurationSkins configurationCentralized software updatesRemote on/off switch via WebReal-time system visualization via the Operator Panel

Previous Go to Index Next

Page 336: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.4_Licensing.htm[24/11/2011 10:24:06 p.m.]

Previous Go to Index Next

6.4 Licensing Elastix is free software distributed under a GPL version 2 license. That is, it can be freely used, copied, modifiedand studied according to the contents of this license. To have access to the complete text of this license, the reader can follow the following link: http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt

Previous Go to Index Next

Page 337: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.5_Elastix.org_Official_project_site.htm[24/11/2011 10:24:07 p.m.]

Previous Go to Index Next

6.5 Elastix.org: Official project site The main resource to which a user can have access when looking for information about Elastix is the officialproject Web site found at http://www.elastix.org In this site the user can find useful support tools, such as:

ForumsWikiLive chatEmail subscriber listsDownload links

Forums One of the most important tools of the Elastix.org website is the forum. The forums are very active and all that isneeded to participate is to register as a user (which is free). Without a doubt, this is the best way to search foranswers to common problems and the developers of Elastix visit this forum on their search for possible bugs.However, the forum is a public place. Therefore, before you participate you have to take into consideration somebasic forum etiquette rules:

Search to check if your problem has already been solved before asking in the forum. Most common problemshave been reported before. Remember this is a public forum. It is possible that you will not get a goodanswer.

Forums are organized a certain way. You should always try to add new comments to the correct category.Otherwise, the forum would be disorganized and the new comment could be ignored.Use correct language to avoid offending anyone. If your message contains offensive language, threatening orbadly intentioned, your message may be eliminated permanently. Civility is a good thing to have if you wishfor other people to collaborate on your problem.

The forum is not an advertising space.

Do not attach images or heavy files. If you wish to upload a file bigger than 2 MB, try uploading it to anotherserver and copying the link.

Use a relevant topic title and if during the discussion the topic changes, open another message to address thenew topic. This will help keep the forum legible.

Previous Go to Index Next

Page 338: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.6_The_Elastix_Web_interface.htm[24/11/2011 10:24:08 p.m.]

Previous Go to Index Next

6.6 The Elastix Web interface It’s finally time to enter the Elastix Web interface. Well, I didn’t really think the reader has gotten all the way herewithout ever entering the administration interface on the Web (at least to look around) but I wanted to say it in thisway to express the importance of this moment. The Web administration interface is the component that defines Elastix. Without this component, Elastix wouldn’tbe what it is, since one of the product goals is the ease of use. Unless it’s some sort of personalized configuration,it’s possible from here to administrate practically everything. You can use any Internet browser to access this interface. However, since the Elastix development team mainlyuses Firefox for its tests, we recommend you use this browser. When you installed your Elastix system you were asked for an IP address for your Elastix system, you need thisaddress now. If you can’t remember the address or you selected DHCP (automatically obtain an address from yourrouter or other DHCP server) then you need to login as “root” at the console with the password you set. Once youdo this, the system will provide you with the IP address of your Elastix system. Now enter this address into your address bar of your Internet Browser, and a screen like the one below shouldappear.

Login screen for the web administration interface

At the moment of installation, the system automatically generated a user named “admin.” This user hasadministration privileges and will allow us to enter for the first time. Take note that the user name is completely inlower case. The password is the same as the one you entered during the installation process (see chapter 5.) Once the name and password are confirmed, the system will show us the administration interface. The first thingwe’ll see is the Dashboard, which is basically a summary screen with some usage statistics and the actual status forthe most important system processes.

Page 339: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.6_The_Elastix_Web_interface.htm[24/11/2011 10:24:08 p.m.]

The Elastix dashboard

What we need to do next is to personalize the interface to our needs. Some suggestions are to check the language,date, system time and time zone are correct, and we could even play around a bit changing the interface’s look-and-feel. All this can be done from the menu “System -> Preferences”.

System preferences

Previous Go to Index Next

Page 340: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.7_Network_configuration.htm[24/11/2011 10:24:10 p.m.]

Previous Go to Index Next

6.7 Network configuration Usually the first important thing that needs to be configured after entering for the first time are the networkparameters due to Elastix using a DHCP server to get IP addresses by default, and this is not ideal if we are goingto implement a unified communications server. It is desirable that we use a static IP address. Configuring the network parameters can be done from the “System->Network” menu. Here we can configure twothings, general network parameters and parameters associated to one of the network cards installed on the server,including those embedded on the mainboard.

Network parameter configuration

To edit the general network parameters click on the “Edit Network Parameters” button that appears on the top partof the previous screen. This will take us to another screen that is shown below:

Basic network parameter configuration

Below the meaning of each of the required fields is explained:

Host: Server name, for example: pbx.example.orgDefault Gateway: IP address for the gatewayPrimary DNS: IP address for the primary Domain Name System (DNS)Secondary DNS: IP address for the secondary DNS

To edit the parameters associated with each network card we must click on the name of each interface. In ourexample we’ll click where it says “Ethernet 0” and we’ll be taken to the following screen.

Page 341: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.7_Network_configuration.htm[24/11/2011 10:24:10 p.m.]

Editing parameters associated with a network card

As we can observe here we can change the IP assigning from DHCP to static, which is what we wanted.

Previous Go to Index Next

Page 342: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.8_Overview_of_the_Elastix_Web_administration_interface.htm[24/11/2011 10:24:12 p.m.]

Previous Go to Index Next

6.8 Overview of the Elastix Web administration interface The Elastix Web administration interface is a complete server administration application for UnifiedCommunications written mostly in the PHP language. In this section, we will do an overview of the most important operations that we can administrate from thisinterface. Also, we’ll explain how the menus and modules in Elastix are organized.

Menus and modules The Elastix Web interface is organized into menus. So we have the first level menus like: System, Schedule, Email,Fax, PBX, IM, etc. and we also have the second level menus, also called sub-menus. A menu can be understood as a container that serves to organize the Elastix interface. A module, however, is an Elastix component that offers us some sort of functionality. The modules are accessibleby menus or sub-menus. In this way, they can be organized inside the Web interface and the user can access themby navigating through the menus. In the following example you can observe that the module “Date/Time” is contained inside the menu (or sub-menu)“Preferences”, which is contained inside the menu “System.” The location of the module can then be referred to as“System Preferences Date/Time.”

Example of a menu, sub-menu and module

On occasion the module can be contained inside a single menu, as is shown in the following figure:

Page 343: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.8_Overview_of_the_Elastix_Web_administration_interface.htm[24/11/2011 10:24:12 p.m.]

Another example of menu and module

Note: It’s important to understand the concepts of module and menu, especially if you are interested inmodifying the Elastix code to perform any customization.

Navigating the Web interface Below we’ll navigate through the Elastix Web interface briefly explaining the meaning of each menu and module.Each first-level menu will appear at the top of a table and each sub-menu will appear in bold type.

Note: It’s important to mention that the following listing only includes the menus installed by default. Thatis, it doesn’t include the menus installed through Addons like the Call Center module, or Web Conference.

System Dashboard Dashboard is a kind of desktop where the

user can see a summary of Elastix’s activitylike the last emails, voicemails, faxes andcalendar dates. The administrator has adifferent interface where he can alsomonitor the system performance and otheruseful functions by adding applets.

Network Network parameters configuration

Network Parameters Specify IP address and network mask,gateway, host name, DNS servers, andothers.

DHCP Server Habilitates the embedded DHCP serverincluded with Elastix

DHCP Client List Shows the list of connected DHCP clients Assign IP Address to Host Assigns an IP Address to a specific client

User Management Elastix User Management Groups Specify User groups Users Administer users and assign them to groups.

Also allows to associate email accounts andtelephone extensions to users

Group Permissions Configuration for the access permissions tothe different modules by a determined

Page 344: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.8_Overview_of_the_Elastix_Web_administration_interface.htm[24/11/2011 10:24:12 p.m.]

groupShutdown Shuts down or reboots the serverHardware Detector Telephony hardware detectionUpdates Software package updating

Packages Package list with the option to install orupdate

Repositories Repository configuration against whichupdates are made

Backup/Restore Generates backups and allows restoring of information for the Elastix server

Preferences Specifies various system preferences Language Changes the language for the whole Elastix

Web Interface Date/Time Changes the date, time, and time zone Themes Changes the themes (skins) to give the

Elastix interface a different look Currency Changes the currency symbol that is shown

in billing reports Dashboard Applet Admin Selection of the applets that are included in

the system dashboard

Schedule Calendar Schedule events in calendar format that can

even generate automatic telephone callsAddress Book Contact address bookRecordings Message recording that can be associated

with events scheduled in the Calendarmodule

Email Domains Email domain creation. Elastix supports

multiple domainsAccounts Email account administration and hard disk

space quota assignmentRelay Relay configuration that allows you to use

Elastix to send email from other networksWebmail Web based email client via RouncubeAntispam Allows SPAM detection in emails and

adjusts its sensibilityRemote SMTP Configure email sending through a remote

SMTP serverEmail list Add mailing list support via Mailman

Page 345: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.8_Overview_of_the_Elastix_Web_administration_interface.htm[24/11/2011 10:24:12 p.m.]

Fax Virtual Fax Virtual Fax administration

Virtual Fax List Listing of virtual fax extensions that willreceive faxes in PDF format via email

New Virtual Fax Creation of new virtual fax extensions Send Fax Sending of a fax from the interface as a

simple text or attached documentFax Master Establishment of an email address that will

receive notifications of fax operationsFax Clients Configuration of access permissions for fax

client applicationsFax Viewer Fax visualization in PDF formatEmail Template Configuration of an email template that will

be sent each time a fax arrives

PBX PBX Configuration Embedded FreePBX application that allows

most of the configurations at the PBX levelOperator Panel Allows the visualization of extensions,

trunks and Queues being used in real-timeVoicemail Voicemail listing. To see it, it must be first

be associated with a user with a telephoneextension

Monitoring Phone recording listing. To see it, it must befirst associated with a user with a telephoneextension

Endpoint Configurator Allows provisioning of a large number oftelephones automatically

Conference Generate audio teleconferencesBatch of Extensions Allows the creation of a large number of

extensions in a short timeTools Access to various useful tools

Asterisk-Cli Execution of CLI commands Asterisk File Editor Test file editing Text to Wav Conversion from text to audio

Flash Operator Panel Flash based operator panel alternative.VoIP Provider Configuration of VoIP trunks with

templates for certain providers

IM OpenFire Embedded interface for IM server

administration called Openfire

Page 346: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.8_Overview_of_the_Elastix_Web_administration_interface.htm[24/11/2011 10:24:12 p.m.]

Reports CDR Report Call detail report (CDRs) with filtering

optionsChannel Usage Channel use reports shows graphs by

different technology type, such as SIP andIAX

Billing Set preferences for billing Rates Establishes rates depending of the mainline

and telephonic prefix Billing Report History of billing with filtering options. Destination Distribution Visualization of a pie chart of the

destination distribution by cost, durationand number of calls

Billing Setup Configuration for habilitated mainlines forbilling and default rates

Asterisk Logs Asterisk logs with filtering optionsGraphic Report Visualization of general data of incoming

and outgoing calls in graphic format forextensions, mainlines and waiting lines

Summary by Extension Summary of incoming calls, outgoing callsand their duration for each extension in agraphic report

Extras vTigerCRM CRM System with Elastix integrationCalling Cards Allows calling card functionality via

A2BillingDownloads Recommended download listing

Softphones Available softphone applications Fax Utilities Available fax applications Instant Messaging Available instant messaging (IM)

applications

Addons Available List of available modules to extend Elastix

functionalityInstalled Listing of installed modules

Previous Go to Index Next

Page 347: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.9_User_administration.htm[24/11/2011 10:24:13 p.m.]

Previous Go to Index Next

6.9 User administration As we already saw in this chapter, Elastix creates by default a user named “admin” that has system administratorprivileges. This user can seem, at first, to be everything we need, but Elastix gives us the possibility of creatingnew users with different levels of privileges, allowing, in this way, for different users apart from the administratorto access the interface, but with limited privileges. For example, we could create a telephone receptionist user that can have access to the operator panel and cananswer, park and transfer calls in a friendly way. We could also create a user for the auditing department withaccess to the different reports like call details and telephone consumption to international destinations. We couldalso create a user for the sales department so that they could access the integrated CRM. In general, Elastix gives us a powerful and flexible permissions system that allows us to create a user for everysingle employee of the company using Elastix.

User groups Every user of the Elastix Web Interface must belong to a group. For example, the user “admin” that we have usedbefore belongs to the group called “administrator.” This group has access to all the Elastix menus. Elastix comes with 3 default groups: administrator, operator and extension. As can be seen at first glance thesegroups serve to create users with administrator, operator and extension privileges respectively.

Group administration

As we can see in the previous figure, it is also possible to create new user groups. Each user group is associatedwith a permissions matrix that we will explain further ahead. In the same way, it is also possible to change theassociated permissions matrix for the default groups. That is why in the paragraphs above we talked about aflexible permissions system.

Group permissions Each group of users has a permissions matrix that associated the user group with the modules to which that groupwill have access. In this way we can configure a custom matrix for each need, only by selecting the adequatemodules. This permissions matrix is configured from “System Administer users Group permissions.”

Page 348: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.9_User_administration.htm[24/11/2011 10:24:13 p.m.]

Group permissions administration

User creation Now that the concepts of user groups and permission groups have been explained, we’ll proceed to create a newuser for the Elastix Web Interface. The users module is found in “System User Management Users”. There we’ll see a listing of active users anda button with the label “Create New User.” We click on that button and access the next screen.

New User creation screen

The following explains the meaning of each field:

Login: The username. It must not contain any blank spaces.Name: The user’s full name. For example “John Smith”Password: The access password.Retype password: The password must be entered again to be verified.Group: The user group to which this user will belongExtension: The PBX extension that will be associated with the user. In this way, when the user enters theinterface he’ll be able to see his voicemails, recordings, call details and other operations related with hisextension.Webmail User: The email user name created by Elastix.Webmail Domain: The name of the email server’s domain.Webmail Password: The password for the email account.Retype Webmail password: The password for the email account must be entered again so it can be verified.

Page 349: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_6/6.9_User_administration.htm[24/11/2011 10:24:13 p.m.]

Previous Go to Index Next

Page 350: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.1_Creating_extension.htm[24/11/2011 10:24:15 p.m.]

Previous Go to Index Next

7Basic PBX Configuration

Education is to elevate man to the level of his own time.-- José Martí

The PBX feature is one of the most important in Elastix. In this chapter we’ll explain how to configure a basicPBX using only the Elastix Web interface. Once done with the PBX configurations we’ll be able to make calls between extensions and use some interestingfeatures like voicemail or music-on-hold. In the following chapters we’ll learn how to connect this PBX to the external world so we can use it in a practicalway.

7.1 Creating an extension Defining and editing extensions is probably the most common task done by a PBX administrator. In version 2.0 ofElastix it’s possible to create five kinds of devices or supported technologies to define an extension: SIP, IAX2,DAHDI, “Custom” and Virtual. To create a “New Extension” we must enter the “PBX” Menu. By default you enter into the “PBX Configuration”section when you select the “PBX” menu. In this section we choose from the left panel the option “Extensions”.Now we can create a new extension. First choose the device from among the available options:

Page 351: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.1_Creating_extension.htm[24/11/2011 10:24:15 p.m.]

Creating a new extension

Generic SIP Device: SIP is the standard protocol for IP phones and ATAs. Most IP phones support SIP.

Generic IAX2 Device: IAX is the “Inter Asterisk Exchange” protocol, a new protocol supported today bysome devices.

Generic ZAP Device: This device is associated with DAHDI channels. It’s a hardware device connected tothe Elastix server.

Other (Custom) Device: Custom allows us to directly write an input into the configuration files, and itfollows that this input must be in the format of an extension that Asterisk will understand. It can also be usedto relate an extension to an “external” number. For example, to route the extension 211 to the number 1-800-555-1212 you can create a “Custom” extension with the number 211 and in the text box of the “dial” fieldyou can input: Local/18005551212@outbound-allroutes.

None (virtual exten): Adds the capacity to create a virtual extension

Below we’ll see the a form that varies a bit depending on what we’ve chosen previously. We’ll assume that theuser has chosen SIP since it’s the most common.

Page 352: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.1_Creating_extension.htm[24/11/2011 10:24:15 p.m.]

New SIP extension creation form

As we can observe you can configure here many interesting things but not all the data is necessary to get afunctional extension so we will only explain the most important ones.

User Extension: It must be unique. This is the number that can be dialed from any other extension. It can beany length but, usually, an extension of two or three digits is used.

Display Name: It’s the Caller ID name so that the calls by this user can be identified by a name. You onlyneed to enter the name, not the extension.

Secret: This is the password used by the telephony device to authenticate with the Asterisk server in Elastix.This is configured generally by the administrator before giving the user the telephone and generally, it’s notrequired for the user to know it. If the user is using a softphone, then he will need to know this password toconfigure his software.

IP telephone configuration To test if the extension created so far works correctly we need to configure an IP phone so that it will register onthe Elastix server (with the created access credentials.) If the reader wants to try this now he can go the chapter 9of this book, where it’s explained in detail how to configure a physical IP phone as well as a softphone installed onyour computer.

Previous Go to Index Next

Page 353: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.2_General_configurations.htm[24/11/2011 10:24:17 p.m.]

Previous Go to Index Next

7.2 General configurations In this section, you can configure general parameters of the Elastix system in regards to telephony. To access general configuration we must go to the “PBX General Configuration” menu. Here we will see thefollowing screen:

General configuration modification form

Below the options of this screen will be explained: “Dial Options”: We’ll explain this in detail briefly.

Page 354: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.2_General_configurations.htm[24/11/2011 10:24:17 p.m.]

“Company Directory” options “Find users in the Company Directory by”: You can listen to the directory of a business by dialing *411 or #when you listen to an IVR. This option configures in which way the users in the directory are located. There are 3ways: spelling the first 3 letters of the last name, spelling the 3 last letters of the first name, and spelling the 3 firstletters of the first name and last name at the same time. “Announce Extension”: When activated the message plays: “Please stay on the line while I transfer your call toextension XXX.” That is, it mentions the extension to which the call will be transferred. This is useful in caseswhere the user doesn’t previously know the extension to which he is being transferred, for example when theoption to be transferred to a sales representative is dialed (ie, option 3). In these cases, it can be useful for the callerto know the extension to which he was transferred so he can remember for future calls so he can skip the IVR. “Operator Extension”: Here you must enter the operator extension, which will be the destination if the callerpresses zero “0.” This destination can be an extension, a group of extensions, or even an external telephonenumber. “Security Settings”: Allows Anonymous Inbound SIP calls. The default setting is “no”. Unless you know thesecurity implications of this option, it is recommended that this be left as “no”. “Online updates”: Check for Updates. Allows automatic checking for available updates. The default setting is“Yes”.

Dial Options As is observed in the previous figure, most of the time this field is filled with the letters “tr.” Here there have reallybeen two options entered, the “t” option and the “r” option, which means that the person that receives the call cantransfer it and that additionally a ring tone will be sent back to the caller. Below is a list of all available options.

A(X): Plays a message to the called person, using X as the file.D(digits): Sends a sequence of DTMF digits after the destination has been answered.h: Allows the called person to hang up by sending the digit “*”H: Allows the caller to hang up by sending the digit “*”r: Sends a ring tone to the calling party.T/t: Allows the parties (caller/called) to transfer calls.W/w: Allows the parties (caller/called) to start recording of the ongoing call, the default code to start callrecording is “*1”.

Previous Go to Index Next

Page 355: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.3_Queues_configuration.htm[24/11/2011 10:24:18 p.m.]

Previous Go to Index Next

7.3 Queues configuration Queues consist of user groups for which there are certain policies (or strategies) defined, mainly in regards toincoming calls. Queues can be created as an extension. The Queue extensions can be static, called “members” (thatis, they have a fixed extension number) or dynamic users, called agents (that is, they can enter the Queue from anyextension.) A policy or strategy defines the way in which incoming calls are distributed to the Queues between members oragents. The Queue policies that Asterisk currently supports are the following:

Ring All (ringall): Rings the extensions of all agents until one answers. This is the default option.Agent with least recent call (leastrecent): Rings the extension of the agent that answered a call leastrecently for this Queue.Agent with the fewest calls (fewestcalls): Rings the extension of the agent that has answered the leastnumber of calls in this Queue.Random (random): Rings extensions randomly.Round Robin with Memory (rrmemory): Rings the extension of each agent in a sequential manner, butremembers which agent answered the last call to ring the next agent when the next call comes in.Linear (linear): Rings the agents’ extensions in the specified order or in the order in which the agents havelogged into the Queue.Weighted Random (wrandom): Rings the agents’ extensions in a random manner but using a penalty as aprobability measure.

To configure the Queue in Elastix we must go to the PBX Module and choose the menu named “Queues.” To add a new Queue we must fill in the following form:

Page 356: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.3_Queues_configuration.htm[24/11/2011 10:24:18 p.m.]

Form for adding a new waiting line

Queue Number:This is the number that must be dialed to enter the Queue. Queue Name:Name for the Queue. This is used only for identification purposes. Queue Password:A Queue can have a password. Any caller attempting to enter that Queue must dial that password. CID Name Prefix:Since an agent can start a session and answer calls from several Queues at once, it’s useful to add a Caller IDprefix to the calls so that when the agent receives the incoming call on his telephone, he can know through thisCallerID that the call belongs to a determined Queue. Static Agents:These are the extensions that will always answer calls that arrive at the Queue. Dynamic Members:Here we specify members that don’t use a fixed extension to answer calls from the Queue, but that must initiatetheir session in the Queue and then can answer from any extension that is available.

Page 357: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.3_Queues_configuration.htm[24/11/2011 10:24:18 p.m.]

Agent Announcement:This is an announcement that is reproduced for the agent before a call is transferred to him. This is useful for whenagents don’t have Caller ID on the telephone and wish to know that a call comes from a specific Queue. Music on Hold Class:Makes it possible to choose what kind of music will be reproduced for the caller while he is in the Queue for anagent. Max Wait Time:It is the maximum time that a call will stay in the Queue. The action to be taken when this time is up is configuredin the “in case of failure destination” section. Max Callers:It is the maximum number of people allowed to wait in the Queue. If this number is reached, the excess calls willbe rerouted to the destination configured in “in case of failure destination.” Join Empty:If you wish callers to enter an empty Queue (without agents,) then you have to change this parameter to “yes.” Thisis not recommended. Leave When Empty:Change it to “yes” if you wish to stop more calls from coming in at the moment when the last attending agent hasleft the Queue. Ring Strategy:There are 7 types of ringing strategy, which were explained previously:

- ringall- leastrecent- fewestcalls- random- rrmemory- linear- wrandom

Agent Timeout:The time an extension will ring for each agent in the Queue before it is sent to another agent. Retry:The time the system will wait after having made all the extensions ring for all member agents before calling themall again. Wrap-Up-Time:After a successful call, indicates the number of seconds before declaring the agent free and sending him a new call.The default value is 0. Call Recording:Option to record calls coming into the Queue

Page 358: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.3_Queues_configuration.htm[24/11/2011 10:24:18 p.m.]

Fail Over Destination:This is the destination if an agent couldn’t attend a call in the Queue.

Previous Go to Index Next

Page 359: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.4_IVR_recording_system.htm[24/11/2011 10:24:20 p.m.]

Previous Go to Index Next

7.4 IVR and the recording system

Recording of the welcome message Before creating an IVR it’s necessary to already have a recorded message that will be reproduced when a call isattended by that IVR. You have two options for this: recording the message from your own extension or loading apreviously recorded audio message.The first option is without a doubt the most comfortable since we can record from the same telephone if the time isshort. However, the second option gives us the possibility of loading an audio file produced in a studio. There arecompanies dedicated to providing these voice recording services for IVRs and depending on our budget they caninclude professional voice actors, background music, sound effects, and other features. To access this module go to the PBX menu and you’ll get by default the “PBX configuration” section, choose inthe left panel the option “System Recordings.”

System Recordings

As previously mentioned, the first option allows us to record the audio directly from a functioning extension. Forthis we enter the extension number from which we want to record into the box that says “If you wish to make andcheck recordings from your phone, please enter your extension number here,” in this case we will use the extension201 and click on the Go button. After doing this, Asterisk will wait for our recording on extension 201. To continue, we pick up the phone on the

Page 360: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.4_IVR_recording_system.htm[24/11/2011 10:24:20 p.m.]

entered extension and dial *77, a beep will be heard which indicates that we can start to record our message. Whenwe are finished recording we press the # key (pound.). We do this for two reasons, one is that it sounds moreprofessional than hanging up with the handset, as there is nothing worse than handset hangup noise at the end ofthe recording, and two, the system will provide you more options in relation to the recording which are described inthe next paragraph To check our recording from this same telephone we dial *99 and it will playback the message as recorded. If youare happy with the result then the next step is to assign a name to the recording in the corresponding box andclicking on the “Save” button. The second option that we have is to load a recording created by another application. For this we need to have anaudio file in a format supported by Asterisk. In the same previous menu click on the button “Choose File” so wecan search for our file and then proceed to name this recording. Finally we click on “Save.”

Configuring a welcome IVR The IVR allows us to receive an incoming call and produce a welcome message. We can also have an interactivemenu through the telephone pad, through the 10 digits, the # symbol (pound) and * (asterisk). With this it’spossible to route the call to another destination or back to the IVR that sent the announcement. To access the “IVR” module, head to the “PBX” Menu and the “PBX Configuration” section will appear bydefault. In the left panel choose the “IVR” option. To record a welcome message, as was explained in the previous section, you must go to the “System Recordings”menu and proceed to the recording of a message. For the creation of an IVR it’s not necessary to fill in all the fields, since in our case (a welcome IVR), we won’need options. The necessary fields are as follows:

Change Name: Give the IVR with a distinctive name.

Timeout: Waiting time (in seconds) before routing the call to an operator after having played theprerecorded message.

Turn on direct dialing: This option allows the caller to dial an internal extension without having to wait forthe operator to answer.

Announcement: It's the announcement or message that you recorded previously. It will show up on a listwith all available messages.

Then you must proceed to configure what will be the destinations of the calls according to the digit that the callerpressed on his phone. For example, generally the digit 0 (zero) makes the call to be sent to the operator extension.It’s possible to configure destinations for the numbers from 0 to 9.

Page 361: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.4_IVR_recording_system.htm[24/11/2011 10:24:20 p.m.]

IVR creation form

Among the available menu options, in the left part there is a box in which you must enter the digit corresponding tothe IVR option. Then you must choose which one will be the call destination. Here you can choose from amongvarious modules that are available in FreePBX, sending the call to a Queue that is already defined, or to anotherIVR, to a ring group, a specific extension, etc. Note that only the options that you have configured already willshow up as destinations. If you have not setup any ring groups, then Ring Groups will not show up as a destination. Finally we save the IVR just created by clicking on the “Save” button.

Previous Go to Index Next

Page 362: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.5_Conference_rooms.htm[24/11/2011 10:24:21 p.m.]

Previous Go to Index Next

7.5 Conference rooms Elastix can administrate two kinds of conference room: Permanent conference rooms and temporary conferencerooms. The first kind can be administered under the “PBX PBX Configuration Conferences” menu, while thesecond can be administered under the “PBX Conferences” menu. Conference rooms are nothing else but a virtual extension through which you can interconnect several calls at thesame time, giving the illusion of being in a conference with many people talking at the same time. A permanent conference room is one that has a definitive pre-assigned number. For example, let’s suppose that wewant to create the 88999 room and assign it to the Operations Manager. From now on the Monday morningtelephone reunions can be realized simply by dialing 88999 when the agreed time comes and all the participantsknow that that room number won’t change from Monday to Monday. A temporary conference room is created, as is obvious, for temporary ends. For example, the company willparticipate in a product demonstration abroad and wants to schedule a series of reunions between the suppliers andexternal assessors so that they can come to an agreement on different topics. So it’s decided to assign a conferenceroom for each assessor so that they can coordinate the conferences that they think necessary. Logically we don’twant the rooms to be permanent but to expire after the convention since they’re not permanent workers for thecompany.

Conference listing

In the present section we’ll explain how to administrate temporary conferences. To enter the conference module you will be able to observe all the concurrent conferences. To visualize past orfuture conferences you must select the corresponding option in the “State” box and clicking on “Show.” Alsoprovided is a filter used on the conference names. To delete one or more conferences we must select them and click on the “Delete” button. If you wish to add a new conference, click on the “New Conference” button.

Page 363: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.5_Conference_rooms.htm[24/11/2011 10:24:21 p.m.]

Creation of a new conference

The required fields to add a new conference are:

Conference Name: Necessary to identify the conferenceConference Number: A random number is provided for the conference. You can change it if it’s not beingused by another conferenceStart Time (PST/PDT): Starting time for the conferenceMax Participants: No more participants can be invited once the maximum number of participants isreached.

To see a conference’s details you can click on the conference name. Below we’ll show the way to administer temporary conferences. To administer a concurrent conference click on theparticipants link corresponding to that conference. To invite someone to the conference you must chose them from the provided list (list of available extensions) andclick on the “Invite Caller” button. You will have to wait until the call is answered. Once you’ve invited someone to the conference they will start to appear on the report. If you wish to silence one orvarious guests, select them in the “Mute” column and click on this button (Mute). You can also expel from the conference one of various guests by clicking on them in the “Kick” column andclicking on this button (Kick). If you wish to expel all the guests in the conference then click on “Kick all”. If someone you invited isn’t showing up on the guest list or someone you kicked is still showing on it, click on the“Update” button. This button will also refresh the time each guest has been in the conference. Note that once you click on the “Mute” button the guest’s state will be refreshed, the possible states are: Muted andUnMuted. To return to the administration interface for all the conferences click on “Cancel”.

Previous Go to Index Next

Page 364: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.6_Call_parking.htm[24/11/2011 10:24:23 p.m.]

Previous Go to Index Next

7.6 Call parking Call Parking is a virtual extension with waiting music. That is, if you call that extension you will hear music onhold. This action is called parking a call. This feature is very useful when we answer a call and must transfer it to an extension to which we still don’t knowthe final destination number. For example, an important call comes in for the Business’ manager and he isn’t in hisoffice. Due to its importance, the operator has to find him, so while she looks for him she can transfer the caller toCall Parking extension so that the caller can wait comfortably with music on hold. Of course, many will say that itcould simply be put on hold but this would occupy the receptionist’s telephone extension possibly blocking newcalls from being answered by the receptionist. Once the missing manager is found he can be told that he has a callparked on extension 71, for example. Then, the manager himself can un-park that call by ringing that parked callextension and restart the conversation from his own extension or from the nearest extension.

Configuration of Call Parking

Enable Parking Lot Feature:By selecting this option you will authorize the call parking feature. Parking Lot Extension:Indicates the extension at which you must call to send a call to park it. Generally it indicates the first slot of callparking channels. Depending on the number of parking slots will be how many numbers you have for this feature. Number of Slots:

Page 365: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.6_Call_parking.htm[24/11/2011 10:24:23 p.m.]

Indicates the number of slots available for call parking. This number represents how many extensions are availablefor parking a call. Parking Timeout:The period of time that a call can last parked. If the call reaches this time in the parking room the call will bereturned to the extension from where it was sent to parking. Parking Lot Context:This is the context that will affect the behavior of parked calls. By default this contains the context “parked calls”and should not be changed. Destination for Orphaned Parked Calls:This is for configuring the destination of a call that exceeds the maximum time that a call can be parked (asconfigured in parking timeout). Some of the possible destinations can be: an announcement, an IVR, terminate thecall, an extension, a queue, a conference or a personalized application.

Previous Go to Index Next

Page 366: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.7_Music_on_Hold.htm[24/11/2011 10:24:24 p.m.]

Previous Go to Index Next

7.7 Music on Hold In this section it’s possible to configure the “Music On Hold” categories that will be available for the differentfeatures that use Music on Hold (e.g. Queues, Calls put on Hold, Conference rooms, etc). The user will hear thesuccessive playing of the files defined here as background music while they wait to be attended. To upload a WAV or MP3 file:Simply with the “Choose File” button you can select the file (in mp3 or wav format) from your local PC’s harddisk. Then you must click on “Upload” and the file should appear on the MOH (Music-On-Hold) file list that isshown below the file loading option. It’s possible to adjust the volume for loaded files using the option “Volume Adjustment” that is found under the“Choose File” button.

Music on Hold administration form

Previous Go to Index Next

Page 367: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.8_Operator_panel.htm[24/11/2011 10:24:26 p.m.]

Previous Go to Index Next

7.8 Operator panel Since Elastix 2.0 the “Elastix Operator Panel” (EOP) has been incorporated as an alternative to the existing “FlashOperator Panel” (FOP.) The reason why EOP was introduced was because the new version of FOP (FOP2) requires a license type that isincompatible with the present Elastix license (GPL version 2). In general the operator panel allows the visualization of the state of extensions, trunks, Queues, conference andparking rooms in the system, all in real-time. It’s a very useful application for a receptionist.

To gain access to the “Elastix Operator Panel” go to the “PBX” menu and click on the “Operator Panel” utility.

Elastix operator panel

Additionally, in Elastix 2.0 the original “Flash Operator Panel” is still available in the “PBX” menu in the “FlashOperator Panel” sub-menu.

Flash Operator Panel

Previous Go to Index Next

Page 368: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.9_Call_transfer_operations.htm[24/11/2011 10:24:28 p.m.]

Previous Go to Index Next

7.9 Call transfer operations By default, in Elastix the call transfer operations are configured as follows:

Blind transfer To transfer a call blindly you must dial ## followed by the extension number to which you will transfer the call.

Attended transfer To transfer a call with attendance you must digit *2 followed by the extension. If you wish to change these codes go to the “PBX PBX Configuration” menu and choose the “Feature Codes”menu. There you will have the options “In-Call Asterisk Attended Transfer” and “In-Call Asterisk Blind Transfer”where you can change the assigned code for transfers both attended and blind respectively.

Feature codes

Note: The transfer methods provided above are the Asterisk standard methods of transferring a call. It should also

Page 369: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_7/7.9_Call_transfer_operations.htm[24/11/2011 10:24:28 p.m.]

be noted that many IP Phones now have their own methods for transferring the calls as well which do notnecessarily utilize the above codes. The IP phones that use their own transfer mechanisms are utilizing the SIPTransfer commands. You can choose the most reliable for your environment, but in an environment where older analog phones are used,which have no transfer capability, using the Asterisk method of transfer is the only option available to them.

Previous Go to Index Next

Page 370: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.1_Types_cards_and_manufacturers.htm[24/11/2011 10:24:28 p.m.]

Previous Go to Index Next

8Hardware configuration

We cannot always oblige; but we can always speak obligingly.-- Voltaire

Even though Elastix can work without any need for telephony hardware to be installed, telephony hardware isnecessary if a direct connection to certain telephony networks, such as the PSTN, is required. Its installation andconfiguration is simplified with Elastix because it has a specialized Web interface that makes this task much easier. In this chapter we will be basically talking about PCI cards (or PCI express.) However, other devices can be usedto connect to the PSTN like gateways, which work through IP, or channel banks that can even operate throughUSB.

8.1 Types of cards and manufacturers In this section we’ll basically be talking about telephony cards, also known as interface cards. This hardware isavailable both for analog and digital telephonic networks and inside each of these categories there are also thefollowing subcategories:

AnalogFXOFXS

DigitalE1/T1/J1BRI

There are many hardware options that are compatible with Elastix, so we should have no problem finding one that

Page 371: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.1_Types_cards_and_manufacturers.htm[24/11/2011 10:24:28 p.m.]

adapts to our needs. To make the decision even easier, Elastix has a hardware certification program that takes charge of put each modelthrough many diverse tests to determine its compatibility with Elastix in agreement with the certification programcriteria. The list of certified hardware is publicly available at the following link: http://www.elastix.org/en/product-information/certified-hardware.html Here we won’t only find interface cards but also IP telephones, gateways, intercoms, channel banks, securitycameras and appliances. It’s also worth noting that if a determined model isn’t listed it doesn’t necessarily mean that it’s not compatiblewith Elastix. Since the certification program stipulates that the testing process can only be done by explicit requestfrom the manufacturer, it could be the case that the model we’re looking for hasn’t been turned over to thecertification process by the manufacturer.

Previous Go to Index Next

Page 372: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/...chapters/chapter_8/8.2_Hardware_installation_for_telephony_hardware_in_Elastix.htm[24/11/2011 10:24:29 p.m.]

Previous Go to Index Next

8.2 Hardware installation for telephony hardware in Elastix Installing telephony hardware in Elastix is a relatively easy task. However, it’s necessary to have some conceptsclear before beginning so that we don’t get confused. To install telephony hardware in Elastix we must follow the following steps:

1) Physically install the hardware2) Detect the hardware drivers3) Configure the Asterisk hardware

Each of these tasks will be explained below.Previous Go to Index Next

Page 373: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.3_Physical_installation_card.htm[24/11/2011 10:24:31 p.m.]

Previous Go to Index Next

8.3 Physical installation of a card This doesn’t involve any complicated task, just the obvious precautions when installing electronic cards in yourcomputer, like having turned off and completely disconnected the power, using an electrostatic discharge device,etc.

Note: In the case of FXS hardware installation, it’s quite common to have to connect a power cable to thecard since we should remember that FXS interfaces need to give electric power to the devices connected tothem.

Analog modular telephonic card with 3 FXO and 2 FXS ports installed

In the above figure we can observe in the lower right hand corner the Molex type connector that serves to give thecard additional power in case we use FXS modules. After installing the card we turn on the computer and we should see the card listed on the PCI bus level. As anexercise we could try using the lspci command (at the Linux prompt) before and after installing the card to see thedifference.

Modular hardware There are manufacturers that design their hardware in a modular way, so that it can be expansible. The modules aresocketed and can be added and removed with careful applied pressure. For example, let’s take a look at the analog card in the following image with a capacity for up to 8 ports. You canclearly see the modules and that the manufacturer has differentiated them: the FXO modules are red and the FXSare green.

Page 374: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.3_Physical_installation_card.htm[24/11/2011 10:24:31 p.m.]

The same card from the previous image with an FXS module extracted

There are also other kinds of cards where even the echo canceller is a module that can be installed easily. In thisway you can get a card with or without hardware echo cancelling.

Previous Go to Index Next

Page 375: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.4_Hardware_detection.htm[24/11/2011 10:24:33 p.m.]

Previous Go to Index Next

8.4 Hardware detection Once the card has been installed, it’s time for the drivers to detect it. The most important telephony driver inElastix is named DAHDI (it’s really a group of drivers). We won’t go into a lot of detail about DAHDI for nowsince the Web administration interface will allow us to remove ourselves from the driver’s work. However, later onwe’ll explain a bit more thoroughly the operation of DAHDI and how it relates to Asterisk.

Note: We should mention that DAHDI isn’t the only telephony driver in Elastix. Even if most hardwaremanufacturers use DAHDI (or have integrated their drivers inside DAHDI,) there are also manufacturersthat provide different drivers like is the case of Sangoma or Rhino Equipment. These drivers are alsointegrated with Elastix.

In the first versions of Elastix the task of detecting hardware was done manually executing some commands fromthe computer terminal. Now it is done with a Web interface that automatically detects hardware and graphicallyshows us the detected hardware. This interface can be reached from the “System → Hardware Detector” menu. To detect new hardware it’s enough to press the “Detect New Hardware” button.

Detección de Hardware Elastix 2.0

In that menu you have the following options:

• “Replace file chan_dahdi.conf”: This file creates a /etc/asterisk/chan_dahdi.conf file in addition to the onesrequired for the DAHDI system (/etc/dahdi/modules.conf and /etc/dahdi/system.conf) that will be processedby Asterisk, containing the configuration of any cards that are detected.

• “Detect Sangoma hardware”: This option activates the function of the “wanrouter” daemon provided bySANGOMA manufacturers for the recognizing of their hardware and its integration with DAHDI modules.

• “Detect ISDN hardware”: This is an option inherited from previous versions of Elastix, used exclusivelyfor the detection of “mISDN” type hardware. Usually this option is used for the detection of BRI cards byDigium and their clones.

For analog and digital telephony cards there is an option on the Web GUI for enabling echo cancelling (software-based) that will be used for each port on the card. To configure echo cancelling click on “Configuration of Span”.

Page 376: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.4_Hardware_detection.htm[24/11/2011 10:24:33 p.m.]

Then the particular configuration for the card will be entered showing each of the ports for the same and adeployable menu for the election of the required algorithm require by each port. Supported algorithms are: OSLEC,MG2, KBL, SEC, and SEC2.

Note: The most commonly used algorithm is OSLEC. You can find more explanation about the echocancelling algorithms and OSLEC in chapter 13.

Echo cancelling algorithms by port

In the following section, all of the necessary synchronization parameters for digital cards will be explained in moredetail. Once the hardware detection action is executed, Elastix creates configuration files with the entered information,adding additional information that will consider it as “usually” correct, named as “by default.” With this default configuration, the user could modify parameters specific to his environment, so that the telephonyhardware is adjusted to his particular environment. These low-level configurations are explained in the nextsection.

Note: At the time of writing, if you press the detect hardware button ALL cards will be redetected and theirdefault setting rewritten. If you had already configured the card previously this configuration will berewritten. Do not forget to make the necessary backups.

Previous Go to Index Next

Page 377: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.5_Telephony_hardware_configuration_on_the_Asterisk.htm[24/11/2011 10:24:34 p.m.]

Previous Go to Index Next

8.5 Telephony hardware configuration on the Asterisk level Up until this moment, the hardware we have configured isn’t connected with Asterisk in any way (unless the“Replace chan_dahdi.conf” button was selected.) Asterisk by omission does not know if the new hardware has been detected by DAHDI unless it is specifiedthrough the /etc/asterisk/chan_dahdi.conf file. We should realize that Asterisk and DAHDI are two separatesoftware packages that know nothing about each other unless we communicate it to them explicitly. Let us see below a simplified view of how Asterisk and DAHDI communicate.

Simplified diagram of how Asterisk and DAHDI are related

We can see in the previous diagram that Asterisk is related to DAHDI through a module (the Asterisk module)called chan_dahdi.so and that this module needs the /etc/asterisk/chan_dahdi.conf file to know how to correctlycommunicate with DAHDI.

Note: Further ahead, we will go into more detail about the /etc/dahdi/system.conf file shown in the previousdiagram.

Before going into detail about the configuration of the chan_dahdi.conf file we need to mention that an easy andautomatic way of configuring our hardware on the Asterisk level is by pressing the “Replace chan_dahdi.conf”button. As the reader will assume, this action replaces the chan_dahdi.conf file with a generic one. However, inmost cases the configuration written in this file will only be useful as an example or as a starting point sinceElastix doesn’t have any way of knowing how we want to group our telephony channels or other settings thatdepend on our specific environment and that are configured in that file. Below we’ll explain how to adequately configure the chan_dahdi.conf file.

Page 378: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.5_Telephony_hardware_configuration_on_the_Asterisk.htm[24/11/2011 10:24:34 p.m.]

Configuration of the chan_dahdi.conf file Asterisk comes with a module called chan_dahdi.so that allows it to communicate with the DAHDI drivers and inthis way connect Asterisk to the telephonic hardware. This module is configured through the chan_dahdi.conffile. In the chan_dahdi.conf file basically the signalization of voice channels is configured and they relate toAsterisk channels with circuits or telephonic lines defined in the driver configuration. These channels can begrouped into what is known as trunks.

Note: The configuration of DAHDI drivers mainly resides in the /etc/dahdi/system.conf file. This file waswritten automatically when we realized the hardware detection from the Web interface.

That is, if I have 15 circuits or telephony lines that terminate on the telephony hardware on your server, you cancontrol them through Asterisk and trunk them. For example, dividing these lines into 3 trunks due to your clienthaving 3 departments e.g. sales, support and finance. Let’s first see a simple chan_dahdi.conf file so we can see the most important parameters and then we’llcontinue by explaining some of these parameters. [trunkgroups] [channels]context=from-pstnsignalling=fxs_ls ; trunk #0group=0language=escallprogress=nocontext=from-pstnchannel=1-5 ; trunk #1group=1language=escallprogress=nocontext=from-pstnchannel=6-10 ; trunk #2group=2language=escallprogress=nocontext=from-pstnchannel=11-15

As your can see above, we’ve configured three trunks. Each trunk starts with the word group and is assigned anumerical identifier. In general you would start with the number zero.

Page 379: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.5_Telephony_hardware_configuration_on_the_Asterisk.htm[24/11/2011 10:24:34 p.m.]

Inside each trunk you can repeat the global values (that is, those that are in the header, outside the trunk definition)and these values overwrite the former. For example, the signalization for a specific trunk could be overwritten. Some important parameters:

signaling This parameter defines the signaling for each channel or group of channels. The most common one we’ll see foranalog circuits is fxs_ls and for digital circuits pri_cpe.

The following represents the possible values for this parameter:

em: E & M Immediate Startem_w: E & M Wink Startem_e1: E & M CAS signalling for E1 linesfeatd: Feature Group D (The fake, Adtran style, DTMF)featdmf_ta: Feature Group D (The real thing, MF (domestic, US)) through a Tandem Access pointfgccama: Feature Group C-CAMA (DP DNIS, MF ANI)fgccamamf: Feature Group C-CAMA MF (MF DNIS, MF ANI)featdmf: Feature Group D (The real thing, MF (domestic, US))featb: Feature Group B (MF (domestic, US))fxs_ls: FXS (Loop Start)fxs_gs: FXS (Ground Start)fxs_ks: FXS (Kewl Start)fxo_ls: FXO (Loop Start)fxo_gs: FXO (Ground Start)fxo_ks: FXO (Kewl Start)pri_cpe: PRI signalling, CPE sidepri_net: PRI signalling, Network side (for instance, side that provides the dialtone)sf: SF (Inband Tone) Signallingsf_w: SF Winksf_featd: SF Feature Group D (The fake, Adtran style, DTMF)sf_featdmf: SF Feature Group D (The real thing, MF (domestic, US))sf_featb: SF Feature Group B (MF (domestic, US))e911: E911 (MF) style signalling. Originating switch goes off-hook, far-end winks, originating sends KP-911-ST, far-end gives answer supervision, Originating-end sends KP-0-ANI-STThe following are used for Radio interfaces:fxs_rx: Receive audio/COR on an FXS kewlstart interface (FXO at the channel bank)fxs_tx: Transmit audio/PTT on an FXS loopstart interface (FXO at the channel bank)fxo_rx: Receive audio/COR on an FXO loopstart interface (FXS at the channel bank)fxo_tx: Transmit audio/PTT on an FXO groundstart interface (FXS at the channel bank)em_rx: Receive audio/COR on an E&M interface (1-way)em_tx: Transmit audio/PTT on an E&M interface (1-way)em_txrx: Receive audio/COR AND Transmit audio/PTT on an E&M interface (2-way)em_rxtx: same as em_txrx (for our dyslexic friends)

Page 380: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.5_Telephony_hardware_configuration_on_the_Asterisk.htm[24/11/2011 10:24:34 p.m.]

sf_rx: Receive audio/COR on an SF interface (1-way)sf_tx: Transmit audio/PTT on an SF interface (1-way)sf_txrx: Receive audio/COR AND Transmit audio/PTT on an SF interface (2-way)sf_rxtx: same as sf_txrx (for our dyslexic friends)

switchtype This parameter is for digital circuits and specifies the kind of PRI switch used. The most common is national andeuroisdn depending clearly on which country we are in. The telephone company should provide this data, so weshould feel free to ask. The possible values are the following:

national: national ISDN type 2ni1: national ISDN type 1dms100: Nortel DMS1004ess: AT&T 4ESS5ess: Lucent 5ESSeuroisdn: EuroISDNqsig: Protocol used in ISDN

Previous Go to Index Next

Page 381: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/...rs/chapter_8/8.6_Digital_interface_configuration_using_DAHDI_configuration_files.htm[24/11/2011 10:24:35 p.m.]

Previous Go to Index Next

8.6 Digital interface configuration using the DAHDIconfiguration files The Web based hardware detection tool that is included in Elastix allows us to detect hardware easily. However,even though the tool can successfully configure digital hardware in many cases, we need to take into account thatthe tool configures using default parameters and may need to be customized according to the real environment yourserver is in. The changes need to be made directly in the configuration files, so that will require a deeper knowledge at thislevel.

Note: In this section, we’re basically talking about T-Carrier and E-carrier circuits based on DAHDIdrivers.

DAHDI driver configuration The telephony driver that we install on the Elastix server should be recognized by the drivers (ex. DAHDI) andthen be activated in the Asterisk configuration. DAHDI reads your configuration mainly from the /etc/dahdi/system.conf file. For digital interfaces, the /etc/dahdi/system.conf file must define spans. A span is a group of digitalchannels. Usually a span represents a digital port on the card. For example, if a card has 4 E1 ports then usually weshould define 4 spans, one for each port. A span defines in one line, which has the following format: span=(spannum),(timing),(LBO),(framing),(coding)

SpannumIt is a unique numeric identifier to tag the span. You must start from the number 1 and go up sequentially inincrements of one. TimingIt’s a digit that defines the way the span synchronization will be handled. The possible values are as follows: Value Meaning0 . DAHDI will provide synchronization timing and send it to the other

side. This is most common when you connect through this span to an oldPBX to which you need to provide synchronization. Normally, if youare connected to a telephony company, we should have no span with

Page 382: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/...rs/chapter_8/8.6_Digital_interface_configuration_using_DAHDI_configuration_files.htm[24/11/2011 10:24:35 p.m.]

this timing value.1 Span uses (Telco/Carrier) as primary source of timing synchronization.2 Span uses (Telco/Carrier) as secondary source of timing synchronization.3,4,5,……,n Span uses (Telco/Carrier) as tertiary, quaternary…. etc. source of timing

synchronization. Note: Only the value 0 can be repeated. The rest of the values starting from one should NOT be repeated.

LBO (Line Build Out)It is a digit that represents the length of the cable between the card and the device (modem) provided by thetelephony company. It can usually be left at 0 with no problem. However, if we have a very long cable we shouldcheck the following table: Value Length of the cable or attenuation level0 0 dB / 0 - 133 feet1 133 - 266 feet2 266 – 399 feet3 399 - 533 feet4 533 - 655 feet5 -7.5 dB6 -15 dB7 -22.5 dB

FramingAs we’ll remember, the digital communications protocols T-Carrier and E-Carrier divide information into frames,where each frames transports a determined number of timeslots. These frames can be of different formats andthat’s what is defined here. The possible values for T1 are d4 or esf, while for E1 they are cas or ccs. CodingIt is necessary to code sent information to make it less susceptible to errors because the data itself is used as asynchronization source (or clock). You can lose that synchronization if long rows of zeros are sent (long segmentswith no voltage variation). To avoid this, the data is codified to avoid transmitting these long rows of zeros. Forexample, b8zs means Bipolar with 8 Zeros Substitution. The possible values for T1 are ami or b8zs, while those for E1 are ami or hbd3. For E1 you may also need to adderror-checking crc4 (Cyclic Redundancy Check 4-bits). After making the changes to the system.conf file, it will be necessary to reboot the DAHDI daemon. If everythinghas been correctly configured, DAHDI has the “lsdahdi” command, which can be executed from the Linuxoperating system console that will show the configured cards and their respective channel state. If even though everything is correctly configured you may still receive alarm signals or errors. Make sure that thereare no problems with the “physical” cabling or the digital trunk provider, who may have a problem on their side. Be aware too, that depending on the carrier, or even the termination equipment that they provide, you may need to

Page 383: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/...rs/chapter_8/8.6_Digital_interface_configuration_using_DAHDI_configuration_files.htm[24/11/2011 10:24:35 p.m.]

use a reverse (crossover) cable. These are not the same as an Ethernet Crossover cable.

Previous Go to Index Next

Page 384: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.7_DAHDI_details.htm[24/11/2011 10:24:36 p.m.]

Previous Go to Index Next

8.7 DAHDI details In this section, we list the names of the most important files that come as a part of the DAHDI and a briefdescription of each one of them.

Configuration files DAHDI files Description/etc/dahdi/system.conf Configuration file where the

signalization for eachtelephony port is detailed

/etc/asterisk/chan_dahdi.conf This file is really an Asteriskconfiguration file that is usedto tell Asterisk to whichDAHDI channels to connectand how.

/etc/dahdi/init.conf This is a file used by theDAHDI startup script(/etc/init.d/dahdi).

/etc/dahdi/modules This file contains the names ofthe DAHDI drivers which arepresent in our system (let usremember that DAHDI iscomposed of several drivers.)This file is read by the DAHDIstartup script to know whichdrivers it needs to load and inthis way to not load all thedrivers, but only the ones thatare necessary.

DAHDI kernel modules

DAHDI kernel module Descriptiondahdi.ko Kernel module (driver) that contains DAHDI’s

main operationdahdi_dummy.ko Necessary driver to provide Asterisk with a timing

source when we don’t have installed cards, due tocards having a timing source via hardware.

DADHI Asterisk modules

Asterisk DAHDI module Descriptionchan_dahdi.so Asterisk module that communicates with the

DAHDI drivers.app_dahdibarge.so Asterisk module that provides the DAHDIBarge

application at the dial plan level. This application

Page 385: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.7_DAHDI_details.htm[24/11/2011 10:24:36 p.m.]

monitors (listens) to a DAHDI channel.app_dahdiscan.so Asterisk module that provide the DAHDIScan

application at the dial plan level. This applicationnavigates between channels and monitors them.

DAHDI commands

DAHDI command Descriptiondahdi_cfg Configures the hardware from the

/etc/dahdi/system.conf configuration filedahdi_monitor Monitors the input and output levels of a DAHDI

channeldahdi_scan Prints the DAHDI spans configurationdahdi_speed Runs performance tests on DAHDI hardwaredahdi_test Tests to see if the DAHDI temporizer is working

properlydahdi_tool Shows the DAHDI interface state. Very useful for

debugging.dahdi_genconf Automatically generates DAHDI hardware

configuration files.

Previous Go to Index Next

Page 386: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.8_Before_DAHDI_machines_using_Zaptel.htm[24/11/2011 10:24:37 p.m.]

Previous Go to Index Next

8.8 Before DAHDI: machines using Zaptel From Elastix 1.5 the Zaptel package was replaced by the DAHDI package. Due to this being a relatively recent itsprobable that in practice we will find those machines that still use Zaptel or information you read on the Web thatrefer to Zaptel. To adequately configure these machines in this section we present a summary of the mostimportant difference among both of these driver packages.

Some name changes to take into account One of the more obvious changes in the migration from Zaptel to DAHDI is the name change in the channels fromZAP to DAHDI; some other name changes that are important to take into account are listed below:

Changes in the configuration files DAHDI file Zaptel file/etc/dahdi/system.conf /etc/zaptel.conf/etc/asterisk/chan_dahdi.conf /etc/asterisk/zapata.conf/etc/dahdi/init.conf and /etc/dahdi/modules /etc/sysconfig/zaptel

Name changes in the kernel modules DAHDI module Zaptel moduledahdi.ko zaptel.kodahdi_dummy.ko ztdummy.ko

Name changes in the Asterisk modules DAHDI module Zaptel modulechan_dahdi.so chan_zap.soapp_dahdibarge.so app_zapbarge.soapp_dahdiscan.so app_zapscan.so

Name changes in some commands DAHDI command Zaptel commanddahdi_cfg ztcfgdahdi_monitor ztmonitordahdi_scan ztscandahdi_speed ztspeed

Page 387: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_8/8.8_Before_DAHDI_machines_using_Zaptel.htm[24/11/2011 10:24:37 p.m.]

dahdi_test zttestdahdi_tool zttooldahdi_genconf zapconf or genzaptelconf

Previous Go to Index Next

Page 388: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.1_Softphone_configuration.htm[24/11/2011 10:24:39 p.m.]

Previous Go to Index Next

9IP telephone configuration

It is hard to wake who pretends to be asleep-- Navajo proverb

Configuring an IP telephone tends to be quite simple. As a minimum an IP telephone needs 3 values to work: thePBX server’s IP (in this case the Elastix server IP,) the user name (usually the extension,) and that user’s registeredpassword (or Secret). Here we will show in detail how to configure a physical IP telephone and another that is software-based(softphone), since softphones have become quite popular in recent times. In these phones, SIP technology will beused for their configuration since it’s the most popular technology today, but you can be sure that the configurationof telephones supporting IAX protocol doesn’t differ much from what is shown here. In general, in this book wewill use SIP protocol for most examples with the exception of those cases where the phones are not connectedinside a local network, in which case it’s preferable to use IAX protocol since it’s not so susceptible to problemsrelated to the translation of IP addresses (NAT.) At the end of the chapter, we will go into detail on how to configure a great quantity of IP phones in a swift simpleway. This method allows us to preconfigure phones from a tool called “endpoint configurator” available in Elastix.

9.1 Softphone configuration Today the use of software telephones or softphones has become very popular, in no small part to the savings thatcan be made not having to buy physical phones. The savings are bigger with more extensions, which make it a verycommon alternative in call centers. Of course, before starting to configure the softphone we have to create an extension in Elastix.

Page 389: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.1_Softphone_configuration.htm[24/11/2011 10:24:39 p.m.]

As an example let us suppose that the extension 5678 has been created, which uses SIP protocol and its assigned“secret” is “8765.” The softphone that we will configure will be Zoiper, available in both a free and a commercial version. The freeversion is enough so that we can talk comfortably from one point to the other, so we will base our example on thisversion. To download Zoiper we need to visit the site http://www.zoiper.com We suppose that the reader has enough skills to install the software without problems. Once installed we execute itand a window like the following will appear:

Initial screen for the ZoIPER software

Next, we press the button with tool figure and enter the options menu. The options screen will display with optionsto configure new SIP extensions and IAX, since Zoiper counts with support for both protocols. In our example, wewill configure an SIP extension, so we will see a screen like the following:

Configuring an SIP account

We will fill this screen with the following information:

Page 390: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.1_Softphone_configuration.htm[24/11/2011 10:24:39 p.m.]

Domain: The IP address or domain name for the Elastix serverUsername: 5678Password: 8765Caller ID Name: The name that will appear on the phones that receive our calls

After pressing the “OK” button, we will go back to the initial Zoiper screen. To complete this process, we needselect the created extension and press the register button. This actually authenticates the extension to the Elastixsystem. Other softphones use a similar concept, but some may perform the registration automatically.

Before registering the SIP account

If Zoiper is correctly registered we’ll observe that beside our account name “Test” the word “Registered” willappear.

After the SIP account has been registered

You can repeat this process to configure another Zoiper softphone using a different extension created in Elastixand then checking to make sure it is possible to make VoIP calls between both extensions. In the example, theextension 5678 receives the call from extension “2222.”

Page 391: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.1_Softphone_configuration.htm[24/11/2011 10:24:39 p.m.]

Call incoming into our softphone

Note: Asterisk gives you the possibility of checking the working of the automatically created extensionsthrough an extension called “ECO.” This extension will answer automatically and reproduce the sameaudio we send.

Previous Go to Index Next

Page 392: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Previous Go to Index Next

9.2 IP telephone configuration To configure an IP phone we need to take into account two aspects:

1. Network configuration2. Device registration with the Elastix server

To better illustrate the points mentioned we will use as an example a Polycom SoundPoint IP 330 telephone.

The Polycom 330 telephone that we will be configuring

Network configuration The network configuration can be realized considering that by default the telephone will get its IP through DHCP,but it is also possible to configure a fixed IP. We will explain both methods. After configuring the Phone’s IP address, we will access the Web administration interface to complete the processby entering the remaining parameters.

DHCP Through this option, the telephone will obtain an IP address automatically. Take into account that the network musthave an operating DHCP server, which is the one that will assign its IP address. This may be already on yournetwork, and may be part of your Network router or a service running on a Windows/Linux/MAC Server on yournetwork. If you do not have one, Elastix has an embedded DHCP server at your disposal, which you can easily beactivated from the Web interface.

Page 393: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Below we will detail how to verify on an IP telephone what IP address it was assigned. Press "Menu Status Network TCP/IP Parameters” In the LCD screen, the IP address will be shown. Let us write it down so that later we can access the phone fromthe Web interface.

Static IP If you need to maintain an exact register of the IP addresses of your phones and/or you want to place your IPPhones in specific segments of the IP network, you must use static IP addresses for your phones. To configure anIP address on the phone, you must enter the IP parameters, network mask, gateway and DNS’s in a different menu.Below are instructions on how to enter each one of them. IP address Since by default the telephone is, configure to receive its IP address via DHCP, below we show the way to changethis behavior to the use of a fixed (Static) IP. In the telephone interface press "Menu Settings Advanced (enter password, Default is 456) Admin Settings Network Configuration DHCP Client Edit Disabled Phone IP Address" Here we proceed to enter the IP address. Network mask If you do not enter the correct network mask, your IP telephone will not be able to register with its Elastix Server.These problems occur more frequently when the IP telephones are in different segments of the network than theElastix Server; it is here where you have to select the right network mask. Select "Subnet Mask” (Enter the network mask) Gateway In the case, your phone needs to connect to a different segment of the IP network from your Elastix server, yourphone must have the correct IP address for the corresponding gateway (generally a router) of that segment, or yourtelephone will not be able to register with the Elastix Server. Select "IP Gateway” (enter the gateway’s IP address) After any changes, we need to select "Exit" and then “Save Config”. We must then wait for the telephone to finishrestarting.

Configuration for registration on the Elastix server This configuration can be made from the phone itself or from a Web browser. In this case, we will use the Firefoxbrowser.

Page 394: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Since we know the IP address for our phone already, we will enter from the Web browser. In the followingexample, our phone’s IP address is 192.168.1.235

Firefox address bar

Before entering the Web configuration interface a dialog box will ask us for the user name and password for thephone. The manufacturer’s default user name and password are “Polycom” and “456” respectively.

Authentication dialog via user and password

Elastix IP server To enter the registration parameters for the Elastix server, we will begin by entering those parameters shown on the“SIP” tab. In this screen, you can configure part of the SIP parameters, such as the SIP server, that is the Elastix Server IPaddress and the “Outbound Proxy” which are the same in our case. The correct configuration is shown in thefollowing figure where we suppose that the Elastix server’s IP address is 192.168.1.160

456

Page 395: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Web interface for configuring the SIP parameters for our phone

We must take into account that the Elastix Server address can belong, or not belong, to our IP network segment. Itis possible that the Elastix Server can be on the Internet; it is also possible to get to it through the configuredgateway. In this same screen, it is also possible to change the port used for SIP signalization with the Elastix Server. If youchange to a different value from the default (5060 UDP), you must make sure that this change was also done in theElastix Server.

Extension To enter the specific parameter for the extension assigned to the IP telephone, select the tab “lines” and configurehere your extension as is shown in the following figure. The parameter “Auth Password” must be the same as theparameter “secret” that was entered when the extension was created in the Elastix Web Interface.

Page 396: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Configuration of the SIP line

Optional configuration In this section we will learn how to configure the Polycom to show the date and time of Elastix. In the menu, we must click on the tab "General" and on the field “SNTP Server" (under the time section) enter theIP address for the Elastix server. Additionally we must select the correct value for our time zone in "GMT Offset"

Page 397: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.2_IP_telephone_configuration.htm[24/11/2011 10:24:43 p.m.]

Configuration for the time server

Note: If when you try to enter one of the available extensions in the Elastix Server (from the phone we’reconfiguring) you hear a busy signal even though all the digits for the destination extension haven’t beendialed, check the “Digitmap” option, inside the section “Local settings” inside the “SIP” menu, or if thatdoesn’t work just delete it completely. This may be called Dialplan on other manufacturers phones.

Changing the digit maps

Previous Go to Index Next

Page 398: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

Previous Go to Index Next

9.3 Using the Endpoint Configurator Ocassionally, the installation of IP telephones is complicated when they are many and even more when theconfiguration is not as trivial as the one on the softphone. As shown in the previous section, some telephonemodels can be configured from a Web interface embedded in the telephone itself. Then there are others that mustbe configured through a telnet session. The Elastix Server has an interface that will allow us to configure many telephones in an easier, swifter manner.This tool is named the Endpoint Configurator. The Endpoint Configurator module first makes a scan of the network or subnet that is provided. Something to noteis that when you enter the module, the default network and subnet are those that are configured in the actual Elastixcentral; the scan is executed on that segment of the network and it gets the internal information of MAC and IP ofthe connected network devices.

Scanning the network in search of endpoints

Note: The MAC address works as unique phone identifier for the endpoint configurator. If the IP addresswere used, this could change over time but with the MAC address this does not happen, as every networkconnectable device throughout the world has a unique MAC address provided by the manufacturer at thetime of manufacture

After obtaining the information for all the endpoints in the network segment, the module tries in an intelligent wayto identify the devices that could be IP phones and in the same way tries to gather information about themanufacturer and model so it can choose which ones to configure by looking them up on its internal database oftelephone models. When it has the telephone group to be configured the information is presented on the Elastix Web interface.Something like the following illustration will be shown:

Page 399: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

Initial listing of telephones found on the network. Not yet configured.

As you can observe in the previous figure, a list of all the phones found in that network segment and that Elastixcan recognize or will be able to configure are shown. As you can see, the report shows the columns MAC address, IP address and Manufacturer, which will help usrecognize what IP telephone it is so we can mentally relate it to its physical location.

Close up view of the MAC address, IP address and Manufacturer fields

Then there are two columns called Telephone Model and User Extension. These columns serve to associate anextension (previously created in Elastix) with a physical telephone. In the list called “Telephone Model”, you canchoose which phone model you want to associate with the extension and only those that Elastix can configure andrecognize are listed. Take into account that to configure the telephones extensions they should have been createdpreviously from the “PBX PBX Configuration” menu.

Note: A limit of this tool is that the extensions must be SIP, as other protocol extensions are not supported.The developers in charge of Elastix development are working to incorporate support for other protocols.

Configuration of an ATCOM telephone, model AT-530 Below we will explain step by step how to configure an ATCOM brand telephone, model AT-530. This is a lowcost telephone model supports both SIP and IAX. To configure it first we elect the model and extension to configure from the list shown in Endpoint Configurator.When a telephone is configured for the first time with this module, this presents a “Not configured” status, whichmeans that the Elastix Server has no configuration for it.

Page 400: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

Line corresponding to the AT-530 telephone detected on the network

You must choose the box found on the left side of the screen and then press the “Configure” button. Immediatelythere will appear a confirmation window in which, if you are sure, you can accept so the configuration processbegins. This can take some time depending on the number of telephones you chose; in this case, since it is anexample, there is only one telephone to configure.

Close up view of the information for the AT-530 telephone

After the process, we’ll see that the page was updated and the telephone status is “Configured without incident”.This indicates that the Elastix Server did several things:

First it created the necessary configuration file(s) in the path /tftpboot/ (path in the Elastix central) andin the case of this example only created the file atc0009455765aa.cfg where 0009455765aarepresents the MAC address for the telephone.

Second, it created a register in the Elastix database to maintain a history of the configured telephone.

Third, through a telnet connection (only for ATCOMs) it loaded the configuration file on the telephone,saved the file and rebooted. Because of this, you will note that the telephone will reboot.

Configured AT-530 telephone

There are certain considerations regarding the telnet connection in ATCOM phones. To be able to establish it youneed the user and password. For simplicity’s sake, Elastix uses the manufacturer’s defaults. In the case of model AT-530, they are user “admin” with “admin” password and in the AT-320, the password is12345678. What this means is that for the Endpoint Configurator to work, if these passwords are not as per thedefaults, the configuration will fail. This is the same for most other makes and models of phones supported byEndpoint configurator. A good practice is always set the IP phones to factory defaults if you have already tried tomanually preconfigure the phones before using the Endpoint Configurator. Coming back to interpreting the telephone status we have:

Page 401: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

Status Color DescriptionNot configured Orange Not configured yet by the

Elastix centralConfigured without Incident Green The central configured the

telephone with no problemsUPDATE: Secrets not equalin FreePBX and Endpoint

Red It is necessary to update. Thereason is that the passwordhas changed in the central(FreePBX) and in theendpoint.db the old one isstill maintained.

If there are no issues our IP telephone is configured and registered to the Elastix Server and when you wish tochange extensions, you go to the endpoint configurator, click a couple of times and it’s ready.

Note: There is a “Deconfigure” button. The action it executes is only at the module level. The Elastix Serverdeletes the historic register relating to the IP telephone in its internal database and deletes theconfiguration files related to the path /tftpboot/. This indicates that the telephone will keep the configurationthat was sent to it since the last update with this tool.

Configuring a Polycom Soundpoint IP 501 telephone Below we will show an example of how to configure a Polycom SoundPoint IP501 telephone. First, we choose the model and extension to configure. As in the case of the ATCOM Telephone, we can assumethat it is the first time that it is being configured from the Elastix Server so we will note the Status is “Notconfigured.”

Line corresponding to the Polycom telephone detected on the network

On the left side we’ll select the box and then press the button “Configure.” Immediately the confirmation windowappears in which, if you’re sure, you will accept and the configuration process begins. This can take some timedepending on the number of phones that you have chosen, in this case because it is an example there is only onetelephone to configure.

Page 402: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

Close up view with the information for our Polycom IP501 telephone.

After this process, we’ll see that the page was updated and the telephone status is “Configured without incident”,this indicates that the Elastix Server realized several actions: First, it created the necessary configuration files on the path /tftpboot/ (path on the Elastix central. These filesin the case of Polycom telephones are detailed in the table shown below: File Description0004f21aeb17.cfg The 0004f21aeb17 represents the MAC address and this file is

a header that tells the telephone what it will do during theupdating and configuration process.

0004f21aeb17reg.cfg Contains information on the extension(s) that the telephone willhave

Polycom A folder that has inside other folders called contacts, logsand overrides

server.cfg Configuration related to the proxy server and SIPsip.cfg All the additional parameter that you wish to configure. For

this it’s good to check the Polycom user manual. Second, in these telephones, there is no telnet connection and until now, it’s not known how to reboot and send theconfiguration files from the Elastix Server as a remote centralized action. Because of this it is necessary to executethe following changes on the Polycom telephone itself:

Choose the kind of provisioning which is TFTP.Enter the Elastix Server IP address.Choose for it to read configuration through TFTP.Restart the Polycom telephone.

These steps are the same in all the Polycom models supported by Elastix. Also, as in the case of the ATCOM brandtelephones, a history is generated in the internal Elastix database, about the configuration of the Polycomtelephone. If there are no incidents then now your IP telephone is configured and registered the Elastix Server and when youwish to change the extension all you need to do is go to the Endpoint Configurator module, click a few times andyou’ll be ready.

TFTP updating TFTP is the protocol used in this case to provide provisioning. It means trivial FTP and is a protocol that requiresno authentication. That is, we need neither a user nor a password to perform a process. Most IP telephones supportthis kind of provisioning to transfer their configuration files from the Elastix Server to their endpoints and viceversa, as in the case of Polycom telephones they also use it to download the contact list and to write logs. The Elastix central is embedded with a service charged with listening and accepting transfers using TFTP protocol. It is in the configuration file /etc/xinetd.d/tftp where the directory is customized for tftp use. In our case,

Page 403: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_9/9.3_Using_Endpoint_Configurator.htm[24/11/2011 10:24:46 p.m.]

it is /tftpboot/.

Customizing configuration files There are times when it is necessary to customize certain settings in the configuration files for the IP telephones. Itis possible that in versions of Elastix beyond 2.0 there will be a tool based on the Web to handle these tasks, but fornow, the reader can do it by editing the template configuration files that are on the Elastix central path /var/www/html/modules/endpoint_configuration/libs/vendors/. In this path, we will find the following:

File DescriptionAtcom.cfg.php In this file, you will find the configuration for some ATCOM

models. To change the configuration it is recommended tocheck the user manuals for the ATCOM configuration files.

Polycom.cfg.php In this file, you’ll find the configuration for some Polycommodels. Since the content of these files is XML, this meansthat you can use the same XML for some models.

Linksys.cfg.php In this file, you’ll find the configuration for some Linksysmodels. We should note that they also are in XML format.

Cisco.cfg.php, In this file, you will find the configuration for supported Ciscomodels.

Aastra.cfg.phpIn this file, you will find the configuration for supported Aastramodels.

Grandstream.cfg.php In this file, you will find the configuration for supportedGrandstream models.

Snom.cfg.php In this file, you will find the configuration for supported Snommodels.

When making changes to these template files, the next time you use the Endpoint Configuration model, yourconfiguration customization will be reflected when configuring or updating your telephones.

Previous Go to Index Next

Page 404: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.1_Call_routing.htm[24/11/2011 10:24:48 p.m.]

Previous Go to Index Next

10Advanced PBX Configuration

If I wait I’ll lose the daring of youth…-- Alexander the Great

10.1 Call routing

Incoming routes This option allows configuring the destination for calls that enter through a specific trunk. When a call enters theserver, Asterisk can note the DID (the number that caller rang to reach you), the Caller ID (the callers number thatthey are ringing from) or the port number through which the call is being received if it utilizes DAHDI-type trunks.

Page 405: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.1_Call_routing.htm[24/11/2011 10:24:48 p.m.]

New incoming route creation form

Description:Tag that identifies the incoming route, e.g. MainNumber DID Number: For Digital lines, the DID information will normally be the phone number that the caller dialed to reach you. Somecarriers pass the entire number including Area Code whilst some omit the area code. Some carriers even pass fewerdigits than that. You need to determine from your carrier (or by viewing the Asterisk logs) what information isbeing passed to your Elastix system. For a peer of SIP or IAX types, the DID (Destination-Inward-Dial) is the destination number for the call. Likedigital lines, it could be the number that the caller dialed or it can be a number assigned by the provider and isgenerally associated to the account number. For example, if your account is '85679432', by entering this numberinto the DID field, incoming calls destined for that account should match up with this information and be routed tothe configured destination. If this field is left blank then it will refer to incoming calls with any destination number,commonly referred to as a Catch-All. Caller ID Number:CID Number is the Caller ID or phone number from which the call received by Elastix originated. This piece ofinformation is not trustworthy since hackers can easily bypass it. If this field is left blank, then it will refer toincoming calls with any Caller ID.

Page 406: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.1_Call_routing.htm[24/11/2011 10:24:48 p.m.]

Alert Info:This option can be used to activate the distinctive rings feature that is supported by some SIP devices. Requiresparticular knowledge of the brand and model of the SIP device Pause Before Answer:This option defines the number of seconds to wait before answering the incoming call. The first purpose of thisoption is to allow devices connected in parallel to this line, like fax machines or electronic security devices, to ringfirst before the PBX processes the incoming call. Privacy Manager:If this option is activated, any call without a valid Caller ID will not be able to be routed to its final destination ifthe Caller ID is not entered manually first. That is, the caller will be asked to enter his number using thetelephone’s number pad. Language: With this field, you configure the language for the messages that will be played for taking care of the call. Write“es” for Spanish or “en” for English Detect Faxes:If this option is activated Asterisk will try to find a fax tone in the call, if it finds a fax tone, the call will be sent tothe default fax extension that’s configured in “General configuration.” Set destination:With “set destination”, we can specify where we want the call to end up, either: an IVR, a ring group, anextension, a miscellaneous destination, hanging up the call or a personalized context.

Outgoing routes Through outgoing routes, we can indicate through which trunk or trunks calls that originate from an internal ElastixPBX extension should be routed.

Page 407: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.1_Call_routing.htm[24/11/2011 10:24:48 p.m.]

Outgoing route creation form

Route Name:In this field, the descriptive name for the trunk is entered to simplify their administration. Route CID:In this field, it is possible to specify the number that will be used by the call as an origin number. This feature(changing the origin number at the will of the PBX administrator) needs to be supported by the provider of thetrunk being used to make the call. Route Password:If we fill this field, each time a call tries to use this trunk, the caller will be asked to enter that same pattern as apassword. If the password is entered correctly, the call is connected; if not then it is discarded. Only numbers areallowed to be entered. Emergency Dialing:With this option, we can specify that the route is for emergency calls. A different Caller ID can be specified. Dial Patterns:The dial patterns is the group or pattern of digits that Asterisk uses to check if the number marked by the internalextension “goes” with the pattern configured on the outgoing route and in this way to determine the channelthrough which the call must be sent. There are rules on how to specify dial pattern, which we indicate below: Pattern DescriptionX Represents any digit 0-9Z Represents any digit 1-9N Represents any digit 2-9[1237-9] Represents any digit between brackets. Represents one or more characters| Separates the number on the left from the dialed

number. For example: 9|NXXXXXX should representthe dialed numbers as “92234567” but should only pass“2234567”

Trunk Sequence:It lists and indicates the order in which trunks will be used. When a dialed number by a caller “goes” with thespecified dial pattern, Asterisk will try to make the call through the trunks specified in this option in the order inwhich they are listed.

Previous Go to Index Next

Page 408: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.2_Trunks.htm[24/11/2011 10:24:49 p.m.]

Previous Go to Index Next

10.2 Trunks A trunk is one that allows a call to be finished at another external VoIP communications system. Some kinds oftrunks are:

DAHDIIAX2SIPENUMDUNDiCustom

Let us see some of the parameters for configuring a DAHDI trunk:

Creation of a new DAHDI trunk

Trunk Description:In this field, a distinctive name is assigned to the trunk. Outbound Caller ID:In this option, it is possible to specify the origin number or Caller ID that the call will use when it uses this trunk. Itis necessary for the provider of the telephone line connected to that DAHDI port to allow Caller ID change.The format used is:

Page 409: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.2_Trunks.htm[24/11/2011 10:24:49 p.m.]

“Caller’s name” <###########> If you do not wish to use a Caller ID, leave this option blank. Maximum channels:This option limits the number of channels that can be used in a trunk. When we say channels, we mean the numberof simultaneous calls that can be made, either incoming or outgoing. Dial Rules:The dial rules indicate how Asterisk should dial to make a call in a trunk. This option can be used to add or removeprefixes. If a marked number doesn’t “go” with the patterns in these rules, it’s dialed as it was entered. The rules can be specified through the following syntax: Pattern DescriptionX Represents any digit 0-9Z Represents any digit 1-9N Represents any digit 2-9[1237-9] Represents any digit between brackets. Represents one or more characters| Separates the number on the left from the dialed

number. For example: 9|NXXXXXX should representthe dialed numbers as “92234567” but should only pass“2234567”

+ Adds a prefix to the dialed number. For example:001+NXXNXXXXXX should add 001 to the number3058293438 when this is dialed.

IAX and SIP type trunks Apart from the configurations shown above, there must be specified incoming and outgoing configurations that aregenerally provided by the voice services provider. The configurations can include username, password, codec beingused, the host with which to register, etc. Example of the detail configurations for Peer: allow=ulaw&alaw&gsm&ilbc&g726&adpcm&lpc10canreinvite=nodisallow=alldtmfmode=infofromuser=myusernamehost=nyc.voicepulse.comqualify=5000secret=mypasswordsendrpid=yestype=peerusername=myusername

Page 410: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.2_Trunks.htm[24/11/2011 10:24:49 p.m.]

It is also possible that a register chain is needed with the following syntax: myusername:mypassword@host

DAHDI trunks DAHDI trunks are those associated with the telephony hardware installed on the machine and use thechan_dahdi.so module. The files associated to these kinds of trunks are /etc/asterisk/chan_dahdi.conf and the filesin the /etc/dahdi/ folder. DAHDI trunks are created through a number associated with the channel position in the hardware.

Custom trunks These trunks are created when uncommon protocols are used in Asterisk, like H323, CAPI, etc. A dial string must be specified. For example: CAPI/XXXXXXX

Previous Go to Index Next

Page 411: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.3_Billing.htm[24/11/2011 10:24:52 p.m.]

Previous Go to Index Next

10.3 Billing The “Rates” utility under the “Billing” menu in the “Reports” tab in Elastix allows us to visualize and configurerates that will be used for call billing.

Listing of defined rates

Visualizing, Editing, and Deleting The View link will take us to a screen where the rate data is shown. To delete a rate, click on the Delete button. You can also modify the values of a rate by clicking on the Edit button. The only values you can change are Name,Rate and Rate Offset.

Rate editing form

Creating a rate To add a new rate click on the button Create New Rate. A form will be shown in which the following fields will beentered:

Prefix: Telephone prefix to which the rate will be appliedName: Rate nameRate: Value of the rateRate Offset: Cost of the connectionTrunk: Trunk from which the call accounting will be taken.

Page 412: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.3_Billing.htm[24/11/2011 10:24:52 p.m.]

Creation of a new rate

Billing report The “Billing Report” in the “Billing” menu in Elastix allow us to visualize details on calls with their respective costand applied rate. The report will change depending on the filtering values:

Start Date: Starting date from which the calls will be selected.End Date: Ending date from which the calls will be selected.Field: Additional filtering fields: Source, Destination, Destination channel.

Billing report

Destination Distribution The “Destination Distribution” option in the “Billing” menu in Elastix allows to visualize with a distribution graphthe outgoing calls grouped by rate. The graph will change depending on the filtering values:

Start Date: Starting date from which the calls will be selected.

Page 413: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.3_Billing.htm[24/11/2011 10:24:52 p.m.]

End Date: Ending date from which the calls will be selected.Criteria: Distribution by Time, Distribution by Number of Calls, Distribution by Cost

Distribution by Time The distribution by time option shows a pie chart of the trafficked time for each trunk. It also shows a list of thetrunks with the most trafficking time.

Pie chart showing the distribution of destinations based on use time

Distribution by Number of Calls Shows a pie chart of the number of calls for each trunk. It also shows a list of the trunks with the most handledcalls.

Distribution of destination based on the number of calls

Distribution by cost Shows a pie chart divided by the summarized cost for each trunk. That is, the cost for all the handled calls iscomputed for each trunk. This calculation is based on the rated entered in the “Rates” menu.

Billing Setup

Page 414: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.3_Billing.htm[24/11/2011 10:24:52 p.m.]

In this option, we have to sections that will be explained below:

Default Rate Configuration The “Default Rate Configuration” option in the “Billing” menu in Elastix allows us to determine the cost perminute and connection for the default route, in other words the rate that will be applied when no other rate to applyto that call is found.

Default rate

Trunk Bill Configuration The “Trunk Bill Configuration” option under the “Billing Setup” menu in Elastix allows us to determine which willbe the trunks that are used to obtain calls for the billing process. The list shows all registered trunks, you must choose those to be used for billing and then click on the button“Billing Capable”.

Billing capable trunks selected with a checkmark

Previous Go to Index Next

Page 415: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.4_Reports.htm[24/11/2011 10:24:54 p.m.]

Previous Go to Index Next

10.4 Reports

CDR Report CDR is an abbreviation for Call Detail Record. The “CDR Report” option in the “Reports” tab in Elastix allows us to view a list with call details.

CDR report

The report changes according to filtering values:

Start Date: Starting date from which the calls will be selected.End Date: Ending date from which the calls will be selected.Field: For filtering - Destination Number, Source Number, Src. Channel, Account Code, Dst. Channel,Company, UserStatus: ANSWERED, BUSY, FAILED, NO ANSWER

Note: This report can be exported in CSV format. This file format can be opened as a spreadsheet to managethe data further e.g. calculate call time averages by extension.

Channel Usage The “Channel Usage” option in the “Reports” menu in Elastix allows us to graphically view the number ofsimultaneous call for each channel.

Page 416: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.4_Reports.htm[24/11/2011 10:24:54 p.m.]

Channel usage report

Previous Go to Index Next

Page 417: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.5_DISA_Configuration.htm[24/11/2011 10:24:56 p.m.]

Previous Go to Index Next

10.5 DISA Configuration The DISA module (Direct Inward System Access) allows users to access by telephone from the outside the servicedprovided by the Elastix PBX, the access is done by obtaining an “internal” dialing tone. With this “internal” tone,the external caller can have the same calling functionalities as if he was inside the facilities. For example, theexternal caller could make international calls via the Elastix PBX (if it is allowed). Normally DISA support is not available for all a company’s employees and a password is necessary to obtainaccess to the “internal” tone. To enter the password, some companies provide a hidden option in the company’smain IVR. In any case, precaution must be taken so that unwanted users who could use it to make calls at thecompany’s expense cannot use DISA access. To configure DISA access we must go to the "PBX -> PBX Configuration -> DISA" menu and we will get ascreen like the following:

Form for creating a new DISA access

DISA name: Distinctive name for the DISA access.PIN: The password so the user can access DISA support (internal tone)Response Timeout: Maximum time that the DISA application will wait for the user to complete the PIN orto dial a destination.Digit Timeout: Maximum allowed time between digits.Require Confirmation: Asks for confirmation before asking for the password.

Page 418: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.5_DISA_Configuration.htm[24/11/2011 10:24:56 p.m.]

Caller ID: If you use this field, all the outgoing calls originated from this DISA will use this number asCallerID.Context: Context used by DISA calls.Allow Hangup: If this option is turned on, the user that is calling from that DISA has the possibility ofhanging up the call pressing “**” to get a new dial tone so he can make a new call.

Then, to make the DISA available from the main IVR, we must modify the IVR adding the DISA access with anew IVR option.

Previous Go to Index Next

Page 419: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.6_Time_conditions.htm[24/11/2011 10:24:57 p.m.]

Previous Go to Index Next

10.6 Time conditions The use of time conditions is a very useful feature for many businesses that want to modify the behavior of theirPBX depending on the time of the day, day of the week, or even the day of the year. For example, company Xwants to make it that calls made to sales at night should not go to the sales waiting line but to a message that isplayed with the office attendance schedule and offering an alternative number for urgent cases; or company Zwants to play a welcome IVR message that is different from the usual one during the weekends, since they havespecial offers for the weekend. Time conditions are a feature that is provided thanks to the integration of Elastix with the FreePBX software. Toconfigure time conditions, it is necessary to know what will be put into place by entering two menus. The firstmenu, “Time Groups” is used to define the different schedules that will be needed to discriminate time conditions,and the “Time Conditions” menu will be used to determine the destination of a call according to the schedulinggroup previously defined. To enter the “Time Groups” utility, you must go to the “PBX -> PBX Configuration -> Time Groups” tab. Herewe will have access to a form that will allow us to establish the time range that will later be used in the “TimeConditions” menu.

Adding a new time group

After defining the “Time Groups”, it is necessary to enter the “Time Conditions” utility to relate this schedulinggroup with an entity like an IVR, an extension, a waiting line, voicemail, etc.

Page 420: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_10/10.6_Time_conditions.htm[24/11/2011 10:24:57 p.m.]

Adding a new time condition

Previous Go to Index Next

Page 421: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.1_FreePBX_basics.htm[24/11/2011 10:24:58 p.m.]

Previous Go to Index Next

11FreePBX internal operation

Liberty is not begged for, it’s conquered-- Eloy Alfaro

11.1 FreePBX basics FreePBX is the Asterisk configuration software that has been integrated as a part of the Elastix distro. Thissoftware generates the configuration files required by Asterisk based on the configuration entered by the user fromthe Web interface. To do this task FreePBX divides it into two steps:

1. Gathers the desired configuration into a configuration database. In the case of Elastix, the MySQL databaseengine is used.

2. Converts the stored MySQL information into configuration files through the retrieve_conf tool.

To illustrate this process, let us see the following figure:

Page 422: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.1_FreePBX_basics.htm[24/11/2011 10:24:58 p.m.]

FreePBX operation and components

Previous Go to Index Next

Page 423: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.2_File_organization.htm[24/11/2011 10:24:59 p.m.]

Previous Go to Index Next

11.2 File organization FreePBX reads and writes information in several directories for its proper operation.Below is a list of the most important ones: Directory Description/var/www/html/admin/ Where the GUI for FreePBX resides/etc/asterisk/ Asterisk configuration files modified by

FreePBX/var/lib/asterisk/agi-bin/ Where the Asterisk AGI scripts reside.

FreePBX counts with some scripts in thisfolder, like dialparties.agi

/var/lib/asterisk/bin/ Some binaries or their correspondingsymbolic links that are used by FreePBX

/usr/local/sbin/ The amportal script is here and can only bemanipulated by root

/var/lib/asterisk/sounds/ Sounds that are used in the FreePBX dialplan

/var/lib/asterisk/sounds/custom/ Sounds that have been created by the user.For example, when a welcome IVR iscreated.

/var/spool/asterisk/voicemail/ Where voicemails are stored./var/spool/asterisk/monitor/ Where voice recordings are stored./var/log/asterisk/cdr-csv/ Where CDR’s are written in text format.

Previous Go to Index Next

Page 424: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.3_Configuration.htm[24/11/2011 10:25:00 p.m.]

Previous Go to Index Next

11.3 Configuration

amportal.conf The file /etc/amportal.conf is a plain text file containing general configuration information read byFreePBX. That is, this is the main configuration file for FreePBX and it can be manually edited if that is needed. In this configuration file is the information for database access (user and password) as well as the authenticationtype the FreePBX will use for its Web users. This file is well documented so we will not go into detail about itsoptions of configuration directives.

Previous Go to Index Next

Page 425: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.4_retrieve_conf_ Dial_plan_generator.htm[24/11/2011 10:25:01 p.m.]

Previous Go to Index Next

11.4 retrieve_conf: Dial plan generator retrieve_conf is a program written in PHP that is charged with generating the dial plan from the informationstored on the database (MySQL in our case.) This program is usually executed from the Web through a PHP scripteach time we click on the FreePBX red bar that says Apply Configuration Changes here. However, retrieve_confcan be launched even from the command line.

Previous Go to Index Next

Page 426: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.5_dialparties_agi.htm[24/11/2011 10:25:01 p.m.]

Previous Go to Index Next

11.5 dialparties.agi This is an AGI script written in PHP. You can open it from the dial plan when you want to make a call. Its maintask is to check the state of the extension, which is being called, and also whatever options could be configured forthat extension (call waiting, call forward, do not disturb). Finally, the script returns that information so that theproper action can be taken like for example returning a busy signal in the case of DND or routing the call toanother extension in the case of call forward. If the extension is available and no options are activated, the call willgo on without any inconvenience. To do its job, dialparties.agi checks the Asterisk database (in the file /var/lib/asterisk/astdb). Below are some diagnostics lines that appear in CLI when trying to make a call. These lines are returned by thedialparties.agi script. dialparties.agi: Caller ID name is 'Pedro Paramo' number is '5454'dialparties.agi: Methodology of ring is 'none' -- dialparties.agi: Added extension 1616 to extension map -- dialparties.agi: Extension 1616 cf is disabled -- dialparties.agi: Extension 1616 do not disturb is disableddialparties.agi: Extension 1616 has ExtensionState: 0 -- dialparties.agi: Checking CW and CFB status for extension 1616 -- dialparties.agi: dbset CALLTRACE/1616 to 5454 -- dialparties.agi: Filtered ARG3: 1616

Note: This script can be overwritten by FreePBX itself for a new one so if changes are made to its code thisshould be taken into account. dialparties.agi is found on the path /var/lib/asterisk/agi-bin/dialparties.agi.

Previous Go to Index Next

Page 427: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_11/11.6_Structure_FreePBX_module.htm[24/11/2011 10:25:02 p.m.]

Previous Go to Index Next

11.6 Structure of a FreePBX module This section’s purpose is so that we can understand better the operation of FreePBX to solve possible problems. FreePBX modules have the following minimum file structure: File name Descriptionmodule.xml Contains the module information in XML formatpage.<module>.php Module’s main file containing the necessary functionality. As can be imagined, the word

<module> should be replaced with the module’s respective name.functions.inc.php Library of PHP functions both for the module’s use and for sharing with other FreePBX

components.install.sql Contains SQL sentences that will be executed on the database when installing the module.

Basically used to create the necessary table for the module.uninstall.sql Contains the SQL sentences necessary to uninstall a module. Basically used to remove

created tables.install.php PHP script to be executed when installing the moduleuninstall.php PHP script to be executed when uninstalling the module

Previous Go to Index Next

Page 428: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.1_Interconnection_between_two_Elastix_servers.htm[24/11/2011 10:25:03 p.m.]

Previous Go to Index Next

12Connecting Elastix Servers

Any power not based in union, is weak-- Jean de la Fontaine

12.1 Interconnection between two Elastix servers One of the advantages of using Elastix is that we can easily interconnect two Elastix servers in remote locations sothat they can communicate with a single dial plan. Below we will see how to interconnect two Elastix servers using a SIP-type trunk. Let us suppose that we want to interconnect an Elastix server in point A with another Elastix server in point B. Theresult must be that a telephone connected to the server at point A can communicate by simply dialing the extensionof a phone connected to the Elastix server at point B and vice versa.

Page 429: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.1_Interconnection_between_two_Elastix_servers.htm[24/11/2011 10:25:03 p.m.]

Interconnecting two Elastix

To implement this, defining two things are required:

1. The SIP trunk between both Elastix servers2. The outgoing routes in each Elastix server

The entire configuration can be done from the Elastix web interface from the PBX -> PBX Configuration menu.

Defining the SIP trunk We define the name of the trunk, which in our case will serve as username for the registration process. We willcreate the trunk from the Elastix at point A as pointA and the one at point B as pointB. See chapter 10 for detailson creating SIP trunks. Then we define the peer details, which in this case will be the following: host=dynamicsecret=welcometrunk=yestype=friend

This configuration of the peer section must be repeated on both Elastix servers. In this example, we have definedwelcome as our secret. Now we need to define the register string using pointA or pointB as username, whatever the case may be. For the Elastix server at point A we need to have: pointB:[email protected]

For the Elastix server at point B it should be: pointA:[email protected]

Page 430: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.1_Interconnection_between_two_Elastix_servers.htm[24/11/2011 10:25:03 p.m.]

Once this configuration is set in both Elastix we can verify from the Asterisk CLI if the SIP trunks are registered.When executing the command sip show registry in the point A Elastix server, we should see somethinglike the following: elastix*CLI> sip show registryHost Username Refresh State Reg.Time192.168.1.240:5060 pointB 105 Registered Fri,11 Apr 2008 10:29:43

The next step is defining the user details in the same SIP trunk creation screen from before. The user sectionestablishes where we want the call to end. In this case, we want it to be accessible to local extensions, so it isenough with adding the primary context from-internal. This indicates that when the call enters through the trunkthe specified context will start. The configuration is as follows: context=from-internalhost=192.168.1.240insecure=verytype=friend

Defining outgoing routes See chapter 10 for details on the creation of outgoing routes.

First, we determine the name of the outgoing route. In this case we’ll specify the outgoing route on the serverat point A as: ElastixB

Then we define the dial pattern. In this case, we will use the following dial pattern: 2|XXX. We are assumingthat to dial to the extensions connected to the Elastix server at point B we need to dial with the number 2first.

Finally, we choose the trunk through which the call must go. In this case we’ll choose the trunk SIP/pointA

Previous Go to Index Next

Page 431: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.2_Connection_call_providers_via_IP.htm[24/11/2011 10:25:04 p.m.]

Previous Go to Index Next

12.2 Connection with call providers via IP The popularity of voice service providers (VSP) has grown incredibly in the last years. These companies provideSIP or IAX connections for local or international calls through the internet at a low cost. In this section, we will establish a SIP connection with a provider that will allow us to make calls inside the UnitedStates. Our goal is to register our SIP trunk with a VSP that allows us to make calls to the USA from any IP telephoneconnected to our Elastix server. To implement this, we have to define two things.

1. The Elastix server SIP trunk2. The outgoing route in the Elastix server

Defining the SIP trunk As we saw before, the first thing we must do is define the name of the trunk. In this case, we will call it VP-SIP-NYC. See chapter 10 for details on the creation of SIP trunks. Now we must define the peer features. This information must be provided by the VSP. In general, VSPs give thesame information for all their users with the only difference being the username and password. As an example, our VSP asked us to configure the SIP trunk in the following way: allow=ulaw&alaw&gsm&ilbc&g726&adpcm&lpc10canreinvite=nodisallow=alldtmfmode=infofromuser=myusernamehost=nyc.voicepulse.comqualify=5000secret=mypasswordsendrpid=yestype=peerusername=myusername

Then we add the registration chain, which in our case is the following: myusername:[email protected]

Page 432: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.2_Connection_call_providers_via_IP.htm[24/11/2011 10:25:04 p.m.]

Defining the outgoing route See chapter 10 for details on the creation of outgoing routes

First, we determine the name of the outgoing route. In this case we’ll name it INTERNATIONAL

Then we define the dial pattern. In this case, we will use the following dial pattern: 00. We are assuming thatto dial to an exterior number dialing two zeros first is required.

Finally, we choose the trunk through which the call will go. In this case we choose the trunk SIP/VP-SIP-NYC

Once this configuration is established we can verify from the Asterisk CLI whether the SIP trunk is registered.When we execute the sip show registry command ion the Elastix server, we should see something like thefollowing: elastix*CLI> sip show registryHost Username Refresh State Reg.Timenyc.voicepulse.com:5060 myusername 105 Registered Fri,11 Apr 2008 10:29:43

When dialing an international number like 0018773527849 the call must be established through this VSP.

Previous Go to Index Next

Page 433: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_12/12.3_Predefined_connection_call_providers_via_IP.htm[24/11/2011 10:25:05 p.m.]

Previous Go to Index Next

12.3 Predefined connection with call providers via IP There is another way of creating SIP trunks to interconnect the Elastix server to a VSP. The VoIP Providerinterface allows us to enter the peer and register chain parameters directly into a form. In addition, we can selectfrom the most common providers that are already setup with predetermined configuration settings. The following image shows the configuration of a SIP trunk with a predefined VSP.

Web interface for configuring VSPs

Previous Go to Index Next

Page 434: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.1_Voice_problem_symptoms.htm[24/11/2011 10:25:06 p.m.]

Previous Go to Index Next

13Voice quality

Quality means doing it right when no one is looking.-- Henry Ford

13.1 Voice problem symptoms Quantifying the problems that affect voice quality is difficult because each person’s perception greatly affects it.The causes of voice quality deterioration are varied and hard to categorize. In this section, we will go over the mostcommon problems explaining their causes and possible solutions.

Echo Echo is one of the most common symptoms and is very easy to recognize. It is produced when a part of theoutgoing signal is reflected in the returning signal. Echo consists of the repeating once, or more times of theconversation, with a certain time displacement. There are many causes for echo but one of the most common is produced in analog lines when the signals areconverted in the hybrid converter or 2 to 4 string converter (See chapter 1 for more details.) This happens becauseit is very difficult to separate outgoing and incoming signals in an effective way. The problem gets worse when the impedance on the telephone line varies much. Many of the telephony cardsavailable for Asterisk do not have a good mechanism for adjusting the line impedance with the card impedance. Forthis reason, a part of the wave is reflected, causing echo.

Note: we should remember that for a receptor to efficiently absorb the power of a received signal, its

Page 435: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.1_Voice_problem_symptoms.htm[24/11/2011 10:25:06 p.m.]

impedance must coincide with that of the line. However, there is a better way to couple these impedances in the best way possible. This can be done with aprogram called fxotune available in Elastix from the command line. Unfortunately, this utility must be executedmanually and with the Asterisk service off. For lines with echo problems, it is recommended to execute it in non-working hours once a week because it can take a considerable amount of time. The command is the following: fxotune -i 5

The fxotune command tries sending a pure signal down the line and listening for the return. It does this many timesfor each line until it finds the best gain value. Finally, this software writes the gain value in the file/etc/fxotune.conf When the execution is done, DAHDI must be told to load the new gain values. We can do that with the followingcommand: fxotune -s

We must execute this always before loading Asterisk so it is recommended to include it at the end of the DAHDIstart-up script found on the path /etc/init.d/dahdi so it is not needed to be manually done each time.

Note: It is very important to note that if you use fxotune to try to couple the lines that the variables txgainor rxgain should not be configured in chan_dahdi.conf since they will be overwritten by fxotune.

The only thing left is to turn Asterisk on as normal. Finally, another cause for echo is of an acoustic nature cause when the sound signal feeds back from themicrophone to the earphone. This is more noticeable when we speak through an amplifier. Of course, the design ofthe phone makes a difference and there are models that induce less acoustic echo than others do.

Low volume level Many low-quality telephone lines damp the signal in a significant way causing us to hear a very low volume. Thisobviously affects the quality of the voice making the conversation be many times unintelligible or that the DTMFtones cannot be detected. Both the reception and the transmission volumes can be amplified through settings in the filechan_dahdi.conf. However, care should be taken because on occasion a low volume means a badly coupledline and a better solution in that case would be to use the fxotune utility to correct the problem. If we arbitrarilymodify the gain parameters, we could make the echo on the line worse. The setting that modifies the gain on the transmission signal is called txgain and for reception, it is rxgain.Both can be edited in the file chan_dahdi.conf.

Voice delay

Page 436: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.1_Voice_problem_symptoms.htm[24/11/2011 10:25:06 p.m.]

Voice delay is the time the voice takes in getting to its destination. Usually the delay is less than a second and if itis less than 200 ms, it is not noticeable. When the delay is over 500 ms the talkers tend to interrupt each other and the conversation overlaps. This can beirritating for communications. It is almost impossible to eliminate delay on the server level since in the great majority of cases it is a symptom ofproblems in the communications network. That is, if you want to eliminate it possible changes to thecommunications network will have to be considered.

Voice distortion There are different problems for this category. The most commons of these is robotized voice. When a codec for bandwidth optimization (ex. gsm) is used, and connectivity is having problems, then the loss ofinformation causes distortion. In these cases, it is advisable to change codec to one that offers less voice compression.

Jerkiness in the communication This bothersome problem is usually related to packet loss in the network. The main causes of packet loss are anelevated latency of a limited bandwidth, among others. Jerkiness can also be caused by an elevated jitter. We willlearn more about jitter in the next section. In any case the usual thing is to look for the cause of this problem on the network first and the not the server.Jerkiness can be caused by server problems when the memory resource and CPU consumption are very elevated. Generally, if the maximum latency (absolute, not average) for the network is 150 ms and the communicationschannel is not saturated then we can be sure that jerkiness in communications is not related to the network.

Previous Go to Index Next

Page 437: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.2_Parameters_related_to_voice_quality.htm[24/11/2011 10:25:07 p.m.]

Previous Go to Index Next

13.2 Parameters related to voice quality in packet networks

Network delay We should point out that we are not talking about voice delay but about the delay of the packets in the network. An easy way to calculate (approximately) the network delay is using the command ping. This command sends testpackets to a destination and presents us with a small statistical summary of the sent packets. The summary lookslike the following: --- ping statistics ---6 packets transmitted, 6 received, 0% packet loss, time 5004msrtt min/avg/max/mdev = 73.055/74.181/74.852/0.710 ms

Here we can see some parameters like minimum, average and maximum delay and its deviation.

Packet loss Sometimes some of the packets that compose a message do not make it to the destination. There can be manyreasons for this, like defective or saturated equipment, losses in the transmission media (badly finished cables,elevated electric noise,) and other reasons. In the ping command summary in the network delay section, we see that it also reports a percentage of packet loss.The ideal is for there to be no packet loss at all (0%.) If there is, it should be investigated why. Even losses of less than 1% can affect IP voice conversation. This problem is even greater when we use codecswith a lot of compression.

Jitter Jitter is an important parameter when talking about voice quality in packet networks. Jitter is defined as thevariability of the network delay and normally is in the milliseconds. This parameter is necessary to analyze the quality of the voice since having a low average network delay is notenough to guarantee a good quality.When there is an acceptable network delay average but with high variability, there is a higher chance that packetswill arrive out of order or with excessive delays. Due to voice communication being in real time, it cannot wait forall the packets to arrive and it will discard those that take longer than necessary. So, if we have a high jitter, it ismore probably that packets will be discarded and that we hear jerkiness in the conversation.

Note: Many people blindly trust in the ping command to get the network delay or even to calculate jitterdoing manual calculation. Even though ping can be used in tight situations, the ping command does not

Page 438: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.2_Parameters_related_to_voice_quality.htm[24/11/2011 10:25:07 p.m.]

send voice packets but ICMP traffic, which does not behave in the same way on the network. Even incertain networks, this protocol can have a bandwidth limitation that is totally different from voice packets.The most exact way to calculate jitter is with real RTP packets, which can be analyzed with a sniffer.

Jitter buffers To minimize jitter’s negative effects some VoIP solutions manufacturers have thought of waiting for lost voicepackets before reassembling the voice signal at the destination. As these packets arrive, they would be reordered toreconstruct the original message. This solution is not free of problems since with this action we are also raising network delay to make the messageget to its destination after reordering. However, the idea is good and practical. Maybe if we wait just the rightamount of time it is probable that a good part of lost packets arrive without significantly affecting delay. A jitter buffer then is a small register where voice packets are temporarily stored for a short while to wait forpossible lost packets. The waiting time is known as buffer size. Asterisk supports the jitter buffer concept and this parameter is configurable at the IAX and SIP protocol level.This parameter can be configured in the corresponding technology files (iax.conf and sip.conf). If you want to make sure that the jitter buffer is activated you can add the following options to the following files. In sip.conf: jbenable=yesjbmaxsize=200 ; Optional (defines buffer size)

In iax.conf: jitterbuffer=yesmaxjitterbuffer=200 ; Optional (defines buffer size)

Image of the working of a jitterbuffer

Previous Go to Index Next

Page 439: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.3_How_to_measure_voice_quality.htm[24/11/2011 10:25:08 p.m.]

Previous Go to Index Next

13.3 How to measure voice quality Measuring voice quality has always been a problem for engineers. The complexity lies in that voice quality is asubjective parameter for the person listening to it. Even the concepts like the understandability of a telephonyconversation vary depending on the language we use. Additionally, our mind plays a series of tricks on us to “makelife easier” that make certain measurements of voice quality hard to get. If the voice gets distorted right beforeending the conversation, it is probable that people will rate the call quality differently than if the errors occurred atthe beginning of the call. This happens because our mind gives more importance to more recent events as opposedto those further in the past. There are also people that will unconsciously justify a certain lack of voice quality in favor of perceived personaladvantages or convenience. An example of this is that people will not complain much about voice quality on cellphones thanks to the advantage of mobility. However, if that same quality was heard on a fixed line it is probablethat they would call the telephone company to complain because their line has bad quality. Said in another way, ashuman beings, we are unconsciously justifying this diminishment in voice quality in cell phones. This is just the tip of the iceberg since there are a series of subjective parameters to identify the quality of the voicethat are somewhat hard to quantify. The important part of this example is to demonstrate what a difficult task it isto measure voice quality. Even so, there are some attempts at standardizing the measurement of voice quality. One of the best known is theMOS scale that is based on subjective measurements. We can also relate the E model since it brings in someobjective parameters like network delay and packet loss. Something interesting about this last model is that itcontemplates the conversion of MOS scale results, which allows us to obtain a standard scale to quantify voicequality.

MOS scale The MOS scale is really a recommendation of the ITU. Specifically the ITU-T P.800 recommendation. This scalewrites down a voice quality scale based on the subjective samples that are realized through a series of techniquesknown as Absolute Category Rating (ACR). For this, a group of people is brought together and they are asked to rate voice quality in a subjective way. Beforestarting the evaluation, they must listen to some previously defined examples from the recommendation so that theusers have a reference frame. Once this is done a series of phrases is transmitted (they are also pre-defined by the recommendation) through thetelephone line and the users proceed to rate the voice quality. The following is a summary of the MOS scale. MOS rating Quality Effort5 Excellent No effort needed4 Good It is necessary to pay attention but no significant

effort is needed.

Page 440: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.3_How_to_measure_voice_quality.htm[24/11/2011 10:25:08 p.m.]

3 Acceptable Moderated effort2 Poor Great effort1 Bad Can’t be understood

A disadvantage of using the MOS scale is without a doubt the quantity of time necessary to determine voice qualityin a simple line. Imagine trying to coordinate a series of tests with a great amount of people whom we would haveto previously train just to evaluate voice quality of a single line.

Model E Model E is a model that is more mathematical and objective for the measurement of voice quality based on somenetwork parameters like network delay, packet loss and jitter.

Note: By saying that this is an objective method, the reader should not think that it is necessarily a bettermethod of voice quality measurement. Voice quality contains an important subjective component, as hasbeen mentioned before. However, many times it is more practical to measure the network parameters tomake a mathematical calculation to approximate the voice quality measurement to the MOS scale.

Model E was also recommended by the ITU and it is recommendation ITU-T G.107. This recommendation saysthat voice quality is represented by an R parameter, which is calculated in the following way:

R = R0 – IS – Id – Ie + A Where,

R0 represents the signal-to-noise ratio

IS represents the degradation the signal suffers when being converted into packets

Id represents the network delay

Ie represents the degradation introduces by network devices and depends on the codec and packet

A represents a safety margin

Simplified formula The ITU recommendation provides us with a more simplified formula to calculate parameter R. It is a less preciseapproximation than the above expression since it supposes some default values. The formula is as follows:

R = 94,2 – Id – Ie

Note: If we are observant we will note that the maximum value that R could have is 94,2. We have defined parameters Id and Ie as network delay and packet loss respectively. However, before we enterthese values into the formula we need to normalize them according to the ITU recommendation.

Page 441: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.3_How_to_measure_voice_quality.htm[24/11/2011 10:25:08 p.m.]

The parameter Id represents network delay and is normalized by the following formula:

Id = 0.024 · d + 0.11 · (d – 177.3) · H(d – 177.3) Where d is the network delay in milliseconds and H( ) is the Heavyside function: H(x) = 0 for x < 0 y 1 for x ≥ 0. When analyzing the Id formula we will notice that there is an inflection value at 177.3 ms. This means that athigher values voice quality is affected at more severe rhythm. This is an interesting piece of data since it allows usto sketch an empirical rule to always keep network delay below 170 ms (approximately.) Finally, we need to calculate Ie so we can replace this value in the formula and calculate R Ie depends mainly onpacket loss and the codec used. To maintain things relatively simple we will use a graph with which we candetermine the approximate value of Ie depending on the two mentioned factors. The table is as follows:

Ie (y) vs. packet loss (x)

This graph was generated from the following approximate value table. The vertical axis represents the Ie parameterand the horizontal axis represents packet loss. Packet loss % Ie [G.711] Ie [G.723.1] Ie [G.729A]0 0 11 151 3 15 182 5 18 204 7 20 258 9 22 2816 20 24 30

We can observe that the more compression is involved with the use of a particular codec, the more it contributes tothe Ie parameter and the less voice quality. Even with zero packet loss, we can observe that some codecs willdiminish voice quality.

Page 442: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.3_How_to_measure_voice_quality.htm[24/11/2011 10:25:08 p.m.]

Translating R to the MOS scale Having calculated the value of R we will proceed to explain how to translate it to the better known MOS scale. The formula is as follows: MOS = 1 ; R < 0

MOS = 1 + 0.035 · R + 7 · R · (R – 60) · (100 – R) · 10 -6 ; 0 < R < 100

MOS = 4.5 ; R > 100 Now we have a practical and objective way to measure voice quality in VoIP installation. In this way, we canmake the necessary adjustments to improve the satisfaction of the telephone users. Example Let us suppose that we have done measurements in a point of the network and we want to determine voice qualityat that point knowing that we use the G.711 codec. The network delay is 143 ms and packet loss reaches 7%. Whatis the voice quality measurement according to the MOS scale? After manipulating the values according to the expressions exposed before, we will arrive at a value similar to whatfollows:

R = 94.2 – 0.024 · 143 – 7.2

R = 83.57 Translating R to the MOS scale, we’ll obtain:

MOS = 4.15 This is an acceptable result (4.15/5.00) since we will have satisfied users.

Previous Go to Index Next

Page 443: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.4_Echo_cancellers.htm[24/11/2011 10:25:10 p.m.]

Previous Go to Index Next

13.4 Echo cancellers

Operation of echo cancellers It is very important to know how echo cancellers work to understand how to get the maximum benefit from themand maybe design our own or modify an existing one in case of it being open source.

There are echo cancellers both in hardware and in software. Generally, it is preferred for echo cancelling to beimplemented in hardware so that it will not overload the server’s processor. The principles of echo cancelling arethe same for both implementations. An echo canceller comes from a very simple logical principle. If echo means that a part of the outgoing signal isreflected in the incoming signal then to eliminate echo it should be enough with subtracting the outgoing signal (ina certain proportion) from the returning signal. Due to echo being a reflected signal that is dampened, the key is in estimating adequately this dampingrequirement. For example, let us suppose that the echo signal is 20% of the original signal. Then we can predictthat by subtracting from the return signal 20% of the outgoing signal we will have eliminated the echo completely.At least in theory, of course. This prediction of the damping factor is a key part of any echo cancelling algorithm and receives the name ofadaptive algorithm or adaptive filter. It is called this because it must adapt the value constantly to obtain betterresults. In the following figure, we will suppose the damping in the reflected signal is represented with α. The receivedsignal is Rx, the transmitted signal is Tx and the signal transmitted with the echo component is Txe.

Basic operation of an echo canceller

However, it is not as easy as is explained here. The echo is not just a dampened return signal but can also bedisplaced in time with a certain delay. Therefore, we also must be able to predict this delay to be able to subtractthe echo signal. Predicting the delay is no easy task and generally, echo cancellers have limits. Checking the signalin search of delay for long lapses of time involves too much work and echo cancellers can stop working.

Note: We should stop for a moment to remember that echo cancellers must work in real time and because of

Page 444: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_13/13.4_Echo_cancellers.htm[24/11/2011 10:25:10 p.m.]

this can’t spend time on complex calculations or they would stop being fast enough and would delay thesending of the voice.

The typical delay values that an echo canceller can manage are 64 ms or 128 ms. Obviously, the smaller the delay,the smaller the work for the echo canceller (in terms of CPU use) but the bigger the possible imprecision. Thismaximum delay time that an echo canceller can tolerate is usually referred to as a tail.

G.168 standard Some years ago ITU launched specifications that define the parameters on what an echo canceller should be. Itcould be said that the document is a recommendation. So, if an echo canceller is in concordance with thatrecommendation it’s said that it is G.168 compliant. However, G.168 is a complex technical specification and it isnot easy to determine if an echo canceller is compatible or not. There are even companies that are dedicated to thetedious work of checking to see if an echo canceller is G.168 compatible or not. We will not go into detail here about G.168 since it is beyond the scope of this book. For more information aboutthe technical details of G.168 we recommend you visit the ITU site (http://www.itu.int).

OSLEC Elastix incorporates an interesting open source software echo canceller known as OSLEC(http://www.rowetel.com/ucasterisk/oslec.html). This echo canceller is part of DAHDI and can be configuredindependently for each channel easily from the Elastix Web Interface. This is an image of the hardware detection interface from where we can activate the echo cancelling support.

Echo cancelling configuration from the Elastix interface

Previous Go to Index Next

Page 445: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.1_SIP_Protocol.htm[24/11/2011 10:25:11 p.m.]

Previous Go to Index Next

14Uncovering VoIP Protocols

When wireless is fully applied the earth will be converted into a huge brain, capable of response inevery one of its parts.-- Nikola Tesla, 1905

14.1 SIP Protocol Session Initiation Protocol (SIP) is a signalization protocol (application-layer control) created to administermultimedia sessions between two or more parts. Contrary to what one may think, this protocol is not the one thattransports the voice itself but is in charge of the necessary communication to establish, modify and end a call. SIP protocol was designed with a premise of simplicity in mind. It is a text protocol with simple communicationmessages. SIP even shares some status codes with HTTP, like the familiar “404: Not found”. SIP is a peer-to-peer protocol. That means that practically all of the logic is stored at the endpoints.

Protocol details

Uses in itself two important protocols:RTP transmits voice and videoSDP negotiates the endpoints’ capacity

The latest version of the standard is RFC3261.Allows to easily understand transmitted messages by sending them as text, which makes debugging easier.

Page 446: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.1_SIP_Protocol.htm[24/11/2011 10:25:11 p.m.]

SIP signalization The SIP protocol uses methods and responses to achieve its operation. A method is a mechanism used to convey anaction. A response, as its name indicates, contains the response to a method.

Methods Method DescriptionINVITE Invites a user to a callACK Abbreviation of acknowledgment sent to

indicate that a message has been received.BYE Ends a connection between users or rejects

a callCANCEL Stops the requirement or search for a userOPTIONS Asks for information about the capacity of

the SIP serverREGISTER Registers the location of a userINFO Interchanges signalization information for a

user in the course of a session

Responses

1xx Informational (e.g. 100 Trying, 180 Ringing)2xx Successful (e.g. 200 OK, 202 Accepted)3xx Redirection (e.g. 302 Moved Temporarily)4xx Request Failure (e.g. 401 Unauthorized, 404 Not Found, 482 Loop Detected)5xx Server Failure (e.g. 501 Not Implemented)6xx Global Failure (e.g. 603 Decline)

Registration The following diagram illustrates the registration of a SIP endpoint against a SIP server. It must be taken intoaccount that this is a simplified view since the registration process must also negotiate the codec being used as wellas other parameters.

Page 447: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.1_SIP_Protocol.htm[24/11/2011 10:25:11 p.m.]

SIP registration

This registration must be done periodically in a way that during the session it’s not necessary to sendauthentication information.

Session After registration, the SIP endpoint can initiate a session (in our case a telephone call). In the following image, we illustrate the specific case of a conversation between two SIP endpoints. Messages suchas ACKs have been intentionally omitted to make legibility better.

SIP session between two IP telephones

We should note that SIP is in charge of signalization only. The voice itself is transmitted through RTP protocol,which we will explain in more detail at the end of this chapter. As we can observe, all communications pass by the Elastix server. That is, Elastix works as a mediator (SIPProxy.)

Asterisk and SIP

Page 448: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.1_SIP_Protocol.htm[24/11/2011 10:25:11 p.m.]

Some details that we must take into accounts when we use SIP protocol with Asterisk are the following:

Previous versions of Asterisk (up to 1.4 even) limited the function of SIP protocol to UDP. In today’sversions of Asterisk, we can even make use of SIP over TCP.

By default port 5060 is used for the SIP service although this parameter can be modified in the filesip.conf

SIP has Network Address Translation (NAT) issues although this problem can be fought with parameterssuch as externip, localnet and nat in the file sip_nat.conf

In Asterisk, it is possible to run a diagnostic of the SIP protocol.

Previous Go to Index Next

Page 449: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.2_IAX_Protocol.htm[24/11/2011 10:25:13 p.m.]

Previous Go to Index Next

14.2 IAX Protocol Inter-Asterisk exchange (IAX) is a signalization protocol created by Mark Spencer, the same creator of Asterisk.Its objective is to solve existing problems with other protocols. This protocol is not an industry standard yet, but itwants to become so, through a standardization process at the IETF. In essence, IAX presents two very interesting advantages over other protocol alternatives, like SIP.

Consumes less bandwidthSolves NAT and firewall problems better via the use of a single port

Let us check each one of these advantage: Consumes less bandwidth While SIP is a text-based protocol, IAX is a binary protocol that has an advantage from the point of view ofbandwidth consumption, since in binary, less bytes will be spent. Also, IAX protocol allows trunking of variousaudio channels in the same data flow. That is, that in the same datagram, you can send several sessions at once.This means a reusing of datagrams, which results in an additional saving of bandwidth. Solves NAT and firewall problems better SIP allows signalization from port 5060 and uses port pairs between 10000 and 20000 for the voice itself. This portseparation tends to cause problems when sending voice communication through a firewall. IAX transmits in UDPand uses only port 4569 to transmit both signalization and voice. This allows communications to be conductedthrough firewalls much easier. The administrator must make sure to open just a single port in the firewall. Also, theIAX endpoint doesn’t need to know anything about the network in which it is operating. This combination ofattributes makes the case where the call is completed but the audio is not received to be eliminated. If we reflect on these advantages, we’ll realize that IAX is perfect for trunking between two Elastix servers. Inother words, when connecting two or more Elastix servers the use of IAX is highly recommended. The actual version of IAX protocol is 2. The former is obsolete, so it’s common to see the name IAX2 as asynonym for IAX.

Phases of an IAX call An IAX call has three phases, which are explained below.

Establishing a call To initiate a call the machine that initiates it (machine A) sends a NEW message to the receiving machine(machine B). This last one responds with the message ACCEPT. After this, machine B will ring its bell waiting for

Page 450: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.2_IAX_Protocol.htm[24/11/2011 10:25:13 p.m.]

the user to life the earpiece. If this happens, machine B will send an ANSWER message to machine A to notify itthat the user answered.

Note: Some ACK messages have been intentionally omitted in this explanation to make it clearer.

Establishment of an IAX call

Ongoing call Once the call is answered by machine B the interchanged of audio is initiated with packets called frames. Theseframes are sent within the same communications flow as the initial signalization.

Hang-up Any of the involved parties in a conversation can send a HANGUP message to end the call at any time.

Hanging up of an IAX call

Frames

Page 451: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.2_IAX_Protocol.htm[24/11/2011 10:25:13 p.m.]

To interchange audio between two participants in a call there can be two kinds of frames used both specific forIAX called full and mini. They are also known as F and M because of their initials. A conversation is composed mostly of mini-type frames, whose advantage is (as the name suggests) of being smalland light. That means that they have a small 4-byte header, which helps save bandwidth. Occasionally there is aninterchange of full-type frames, which additionally have synchronization information to keep both pointssynchronized. 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| Origin number |R| Destination number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time-stamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | OSeqno | ISeqno | Frame type |C| Subclass | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | : Data : | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Full-type frame

1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| Origin number | time-stamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | : Data : | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Mini-type frame

Previous Go to Index Next

Page 452: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.3_RTP_protocol.htm[24/11/2011 10:25:14 p.m.]

Previous Go to Index Next

14.3 RTP protocol RTP is the protocol that is charged with transporting voice itself. Many people get confused and think this is whatSIP does, but that is not right. As we have seen before in this chapter, once SIP establishes that a call is made, RTPtakes charge of transporting voice to its destination. RTP works on UDP so there is not much transmission control. This implies the sending equipment sends the voiceto the other end with only the hope that it will arrive. Therefore, it does not expect to receive confirmation of thereceived message since voice needs to be transmitted in real time and any delay can compromise voice quality. If avoice packet is lost in the way that space is simply filled with silence. Technically this is called comfort noise. It is because of this necessity to transmit data in real time that it is obvious that RTP is an acronym for Real TimeProtocol. RTP works with the help of another protocol called RTCP. This protocol is not complete indispensable but it givesvaluable help at the moment of transporting voice optimally since it gives statistics and control information. Thisinformation itself allows the involved voice devices in the conversation to make decisions to better the transmissionin case it is possible. For this effect, RTCP packets are transmitted periodically.

Structure of an RTP packet An RTP packet is composed of a header and the payload. The following diagram illustrates the structure of theheader in RTP packets.

Byte 1 Byte 2 Byte 3 Byte 4V=2 P X CC M PT Sequence number

TimestampSynchronization Source (SSRC)

Contributing Source (CSRC)Extension (optional depending on Bit X)

Data These fields are defined as follows:

V is the version number. This field is 2 bits long and its value is always the number 2.P is a bit that indicates if there is padding at the end of the date. Padding is nothing more than additional bitsat the end of a payload used to accommodate certain encrypting algorithms that expect a fixed size payload.X or extension is a bit that indicates if there’s an extension of the headerCC is a 4 bit identifier that indicates the CSRC countM marker of one bitPT or payload type is a 7-bit identifier that indicates the kind of payload that this RTP packet contains.

Page 453: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.3_RTP_protocol.htm[24/11/2011 10:25:14 p.m.]

Examples of types are G729, GSM, PCMU (G711 u-law), and others.Sequence number: Is a whole number that identifies each packet in the present data flow. This sequentialidentifier goes up by one for each transmitted packet. It occupies 16 bits.Timestamp represents the point in time in which the data sampling was started to transmit in the payload. Itoccupies 32 bits.SSRC identifies the synchronization source since the same device may be communicating with different RTPpacket sources. It is a random 32 bit number for which there is the possibility (although low) that this numberwill repeat in two sources. There are mechanisms to solve this problemCSRC is a 32-bit number that identifies the sources contributing to the payload.Extension is a field of variable length that allows extending the header functionality. This information isonly attached to the RTP header if the bit X indicates so.

After the header, the data must be transmitted; this is nothing more than the audio properly converted to digital andcodified. We should remember that RTP uses two ports for communication, one for going and one for returning. This pair ofports is negotiated when the call between the points is established but in the case of Asterisk, it is between theranges of 10000 and 200000. However, this can be configured in the file /etc/asterisk/rtp.conf.

Previous Go to Index Next

Page 454: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_14/14.4_SRTP_Protocol.htm[24/11/2011 10:25:15 p.m.]

Previous Go to Index Next

14.4 SRTP Protocol SRTP or Secure RTP is, as its name indicates, an alternative to RTP when we need to encrypt the transmittedinformation. In our case, it becomes useful when it is necessary to guarantee that a call will not be listened to by aninterceptor, maintaining the information confidential. From the point of view of a real time protocol, it becomes difficult to conceive of a data encryption that does notadd delay to the communication. If each packet must be encrypted in the origin and decrypted in the destination,without a doubt this will add an additional delay, depending on the power of our CPU, which is the one that willrealize the necessary math for the data encryption. Also we can think that the use of encrypting algorithms will addadditional bandwidth which is always undesirable. All of the above fears are valid and were in the mind of the people that designed the protocol. That is why if weread the official document where the protocol is defined (RFC 3711) we will see that apart from the obvious SRTPobjectives (confidentiality of the information and data integrity) these others are defined:

• Low impact on bandwidth• Low computational cost

In general, we can say that they did a good job and the protocol does not add a significant bandwidth or computingcost so in most cases we can implement SRTP without fears. SRTP is available natively in Asterisk from version 1.8 and activating it is pretty easy. For example, if thecommunication is SIP it’s enough adding to the configuration at each endpoint the parameter encryption=yes

Previous Go to Index Next

Page 455: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.1_Interpreting_log.htm[24/11/2011 10:25:16 p.m.]

Previous Go to Index Next

15Basic problem diagnostics

If I’d asked people what they wanted, they would have asked for a faster horse-- Henry Ford, founder of the Ford Motor Company

15.1 Interpreting the log It is very important to understand how to read Asterisk’s log files since from there we can extract very valuableinformation in our diagnostic process. The level of detail and the kind of information in the log files are controlled from the file/etc/asterisk/logger.conf. This is a plain text file where the names of the log files and the level ofdetail written into them are defined. This is done in single line, with the following syntax: File name => Debugging levels

Where the debugging levels are separated by a comma and can be the following:

debugnoticewarningerrorverbose

Page 456: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.1_Interpreting_log.htm[24/11/2011 10:25:16 p.m.]

Note: There is a special kind of reserved file name called “console.” This name represents the asterisk console,that is, what is shown in the Asterisk CLI.

The following is a fragment of the contents of the logger.conf file that is distributed with Elastix. ; Directory for log files is configures in asterisk.conf; option astlogdir;[logfiles];; Format is "filename" and then "levels" of debugging to be included:; debug; notice; warning; error; verbose;; Special filename "console" represents the system console;;debug => debug; The DTMF log is very handy if you have issues with IVR’s;dtmf => dtmf;console => notice,warning,error;console => notice,warning,error,debug;messages => notice,warning,errorfull => notice,warning,error,debug,verbose

In the previous example, we see come commented lines and a single activated log file names full. This one, aswell as other files defined in this way, is in the path /var/log/asterisk/.

The /var/log/asterisk/full file According to the logger.conf file, Elastix activates by default the log file fullwhere Asterisk writes information about its operation. Each line of this file has the following format: [TIME DATE]LEVEL[PID]FILE_NAME: MESSAGE Below we will see an example of the Asterisk log file.

Page 457: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.1_Interpreting_log.htm[24/11/2011 10:25:16 p.m.]

Log file /var/log/asterisk/full

Log monitoring It is very important to follow the Elastix server’s activity in real time. Many times we’ll find ourselves doing thiswhile we make or take a call to find out what went wrong. The following is a useful method to interactively check the log file full as it is being written with Asterisk’smessages. tail -f /var/log/asterisk/full

If we want to interactively see only the errors, we can add the following filter: tail -f /var/log/asterisk/full | grep ERROR

If we also want to see warnings, we can slightly alter the filter in the following way: tail -f /var/log/asterisk/full | grep -E "(ERROR|WARNING)"

Note: If we want to check the whole log instead of doing it interactively we need to replace the commandtail –f with the command cat

What information can the MESSAGE field give us? MESSAGE refers to the information that is at the right side of each log line, after the file name. If it is an ERRORor WARNING line here, we will find a brief explanation of the error that occurred or of the warning. However,there are other lines with messages that are less obvious and that simply describe the processing of a call throughthe dial plan. These lines are usually marked with a VERBOSE level since they are simply informative.

Page 458: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.1_Interpreting_log.htm[24/11/2011 10:25:16 p.m.]

These VERBOSE level lines (and other informative lines) give use very useful information for problemdiagnostics. Especially useful are those that start with the word Executing since they then mention the context and priority inwhich Asterisk is processing the dial plan. The syntax for these lines is the following: [TIME DATE] VERBOSE[PID] logger.c: -- Executing [extension@context:priority]MORE_TEXT MORE_TEXT can contain information about the application that was executed and the parameters that itreceived. Let us see an example of this: [Oct 28 17:52:34] VERBOSE[22034] logger.c: -- Executing [s@macro-dial:7]Dial("Local/502@from-internal-e27c,2", "SIP/502|21|trTWuwM(auto-blkvm)") in newstack

In this example, we see that when this log line was written we were in the macro-dial context (a macro, since itstarts with the word macro.) Also, the extension was s and the priority was 7. We can also observe that it is tryingto dial with the application Dial() using certain parameters. In any case, we can observe that there is a lot of usefulinformation that we can obtain from each written line in the log.

Process number (PID) Asterisk is multiprocessing software. This means that it can create several instances of itself that will work in acoordinated way between themselves to execute different tasks at the same time. When Asterisk writes a line in thelog, it also writes the process number (PID) that wrote it. This gives us valuable information since we can have amore exact view of the call process. To do this we can filter the PID if we know it. cat /var/log/asterisk/full | grep 38484

With the above command, we were filtering the output to show process 38484. Of course, we could also captureanother chain of characters that matches with the pattern 38484. However, these lines are irrelevant and can bediscarded manually. Thanks to this, we can filter the process of a call and isolate it to find errors. This is particularly useful in anenvironment with a high number of simultaneous calls due to the high quantities of information that Asterisk writesinto the log.

Note: Something important to take into account is that a call can have more than one process (and PID)involved.

Previous Go to Index Next

Page 459: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.2_Diagnostics_through_CLI.htm[24/11/2011 10:25:18 p.m.]

Previous Go to Index Next

15.2 Diagnostics through the CLI From the Asterisk CLI we can see Asterisk’s operation in real time. It’s something similar to "tail -f/var/log/asterisk/full" but with the advantage of seeing the output text bolded (for better reading.) Also,the CLI allows us to interact simultaneously with Asterisk by executing some commands from the console. Elastix gives us a direct interface to the Asterisk CLI found in PBX->Tools and based on the Web. Using the CLIfrom the Web Interface can be very comfortable since you do not have to start a SSH session, which many times isrestricted for remote connections. It should be noted that from the Web interface it is not possible to have aninteractive CL. This is the main difference between executing the CLI from the command lines as opposed toexecuting it from the Web. To access the CLI from the command line it is necessary to execute the following. asterisk -r

Following is an example of the execution of the “help” command from the Elastix Web Interface.

Executing the CLI from the Elastix Web Interface.

Previous Go to Index Next

Page 460: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_15/15.3_Sniffing.htm[24/11/2011 10:25:19 p.m.]

Previous Go to Index Next

15.3 Sniffing The term sniffing describes how packets are captured from the network in their original format for later analysis.There are specialized tools for this end and some can cost a real fortune. Luckily, there are open source solutionsthat do a great job, as is the case of Wireshark. Wireshark was previously known as Ethereal. This powerful sniffer contains advanced analysis tools that allow usto analyze RTP and SIP packets, among others. To capture the details of a call and analyze it we must first define the server’s network card in which we will listen,if there is more than one. Packet capture itself is very easy and we only need to execute Wireshark by following theinstructions. After the capture is ended, it is probable that along with the voice packets we captured other packets that werecirculating the network. Many of these packets, like ICMP, DNS and SMTP are not interesting for our purpose butwith practice, filtering these irrelevant packets is something that we should learn.

Previous Go to Index Next

Page 461: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.1_Asterisk_AGI.htm[24/11/2011 10:25:20 p.m.]

Previous Go to Index Next

16Asterisk external control

Respect is something that is earned, not something that is demanded of others.-- Anonymous

Many times editing the dial plan is not enough and a more flexible mechanism is necessary to handle what thecompany needs. On other occasions, we would even like to control Asterisk in real time through a remoteapplication. To expand the behavior of Asterisk beyond the dial plan there are two very useful interfaces called AGI and AMI.These interfaces allow us to interact with Asterisk at a level that is much more powerful than the one achieved untilnow.

16.1 Asterisk AGI Asterisk Gateway Interface (AGI) established a way to interact with Asterisk from a command line program. Thisprogram can be written in practically any programming language and is invoked by Asterisk from the dial plan. At the moment of invoking an AGI program, certain parameters are sent to it and it responds with AGI commandsthat are understood by Asterisk. The AGI usefulness is huge and allows us to develop extra functionality for our PBX. A common example of thisis the development of applications for the telephonic query of databases. AGI programs or scripts are very popular. Elastix comes with some of these scripts preinstalled by default in thefolder /var/lib/asterisk/agi-bin/

Page 462: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.1_Asterisk_AGI.htm[24/11/2011 10:25:20 p.m.]

Execution of AGI scripts AGI scripts communicate with Asterisk through the file descriptors STDIN, STDOUT and STDERR. This meansthat they should be executable from the same command line. Something very important that should be mentioned is that AGI scripts need to have execution permission for theasterisk user and group so that they can run. We can assign permissions in the following way: # chown asterisk.asterisk script_prueba.agi# chmod 755 script_prueba.agi

After this, we can execute the AGI script from the dial plan so it can do something useful. It does this thanks to theAGI() function. Below is an example. exten => 6789,1,Answerexten => 6789,2,AGI(script_prueba.agi)

As we see in the above example, we have told Asterisk to execute the script called script_prueba.agi. Thisscript will execute when the user dials the extension 6789. By default Asterisk will assume that the script is in thepath var/lib/asterisk/agi-bin/ although another path can be specified with the AGI() function.

Parameters sent to the AGI() script As we had said before, Asterisk sends certain information to the AGI script when it is invoked. Below is anexample of the information sent to the script dialparties.agi, which is a component of FreePBX when weexecute it. agi_request: dialparties.agiagi_channel: SIP/4444-08d6ab60agi_language: enagi_type: SIPagi_uniqueid: 1222117320.271agi_callerid: 4444agi_calleridname: Edgar Landivaragi_callingpres: 0agi_callingani2: 0agi_callington: 0agi_callingtns: 0agi_dnid: 216 6agi_rdnis: unknownagi_context: macro-dialagi_extension: sagi_priority: 3agi_enhanced: 0.0agi_accountcode:

In addition to the information Asterisk sends the AGI script by default, we can send it additional informationinvoking the AGI() function with certain parameters, in the following way:

Page 463: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.1_Asterisk_AGI.htm[24/11/2011 10:25:20 p.m.]

exten => 6789,1,Answerexten => 6789,2,AGI(script_prueba.agi|param1|param2|param3)

In the above example, the additional parameters param1, param2 and param3 were sent to the script. The scriptcan receive as many parameters as is necessary.

AGI commands As a reference for the reader, below we will show a list of the available AGI commands in the latest version ofElastix. This list has been generated with the command agi show commands from the CLI. Command Descriptionanswer Answers the channelasyncagi break Interrupts the Async AGIchannel status Returns the status of the connected channeldatabase del Eliminates a code/value from the databasedatabase deltree Eliminates a tree code/value from the

databasedatabase get Obtains a value from the databasedatabase put Adds/updates a value on the databaseexec Executes an applicationget data Listens for DTMF tones on a channelget full variable Evaluates a channel expressionget option File stream, listens for DTMF, with timeoutget variable Obtains a channel variablehangup Hangs up the current channelnoop Does nothingreceive char Receives a character from the channels that

support itreceive text Receives text from the channels that

supports itrecord file Records a filesay alpha Vocalizes a chain of characterssay digits Vocalizes a chain of digitssay number Vocalizes numberssay phonetic Vocalizes a chain of characters phoneticallysay date Vocalizes a datesay time Vocalizes a timesay datetime Vocalizes a time in a specific formatsend image Sends images to the channels that support itsend text Sends text to channels that support itset autohangup Auto hangs up a channel after a certain time

Page 464: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.1_Asterisk_AGI.htm[24/11/2011 10:25:20 p.m.]

set callerid Specifies callerid for the current channelset context Specifies a context for the current channelset extension Changes the channel’s extensionset music Starts/stops the waiting music generatorset priority Specifies the priority in the dial plan for the

channelset variable Specifies a channel variablestream file Sends an audio file in the channelcontrol stream file Sends an audio file in the channel and

allows the receiver to control the streamtdd mode Changes TDD more (for deaf people)verbose Writes a messages in the verbose log file

for Asteriskwait for digit Waits for the entering of a digitspeech create Creates an object for speech recognitionspeech set Specifies an option for the voice recognition

enginespeech destroy Destroys an object for speech recognitionspeech load grammar Loads a vocabularyspeech unload grammar Unloads a vocabularyspeech activate grammar Activates a vocabularyspeech deactivate grammar Deactivates a vocabularyspeech recognize Speech recognitiongosub Executes the dial plan subroutine

AGI libraries Even though an AGI script can be written in practically any language, some languages already count with librariesto facilitate development tasks. Some of those languages are the following:

PerlPHPPythonRubyC.NET

For more information on libraries or frameworks that are available for these languages, we recommend you checkthis link: http://www.voip-info.org/wiki-Asterisk+AGI In our case, we will use a PHP library called phpAGI with which we will code a simple sample AGI script in thenext section:

Example of a simple AGI script

Page 465: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.1_Asterisk_AGI.htm[24/11/2011 10:25:20 p.m.]

To better illustrate how an AGI script works, we will code something very basic. This script vocalizes a numberwhen we dial a specific extension. Following the PHP code: #!/usr/bin/php -q <?php echo "SAY NUMBER 1234 \n"; sleep(4); ?>

We can save this code as simple.agi in the standard path /var/lib/asterisk/agi-bin/ Once saved, we must make sure that the script can be executed by the asterisk user in the asterisk group. As wehave explained before, this is done in the following way: chown asterisk.asterisk /var/lib/asterisk/agi-bin/simple.agichmod 755 /var/lib/asterisk/agi-bin/simple.agi

Finally, we must modify the dial plan to invoke our AGI script when a specific extension is marked. We will useextension 6789 for this example: exten => 6789,1,Answerexten => 6789,2,AGI(simple.agi)exten => 6789,3,Hangup

These instructions can be found at the end of the file /etc/asterisk/extensions_custom.conf, sincethat file isn’t overwritten by FreePBX. Ready! Dial extension 6789 and you will hear the code say: “one two three four”.

Previous Go to Index Next

Page 466: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

Previous Go to Index Next

16.2 Asterisk AMI The Asterisk Manager Interface (AMI) establishes a way to communicate with Asterisk through IP protocol. Let us say that it is asimilar concept to AGI but oriented towards execution from remote devices. It is this last thing that turns it into a powerful tool. With the functionality, that AMI provides powerful client applications can be developed that can be executed in other computersthus freeing the Asterisk server’s load. One example of what can be done with AMI is the call center module that is a part of theElastix project. This Elastix module is coded using mostly AMI. Due to AMI allowing remote devices to control the Asterisk operation, it is required for these devices to authenticate themselves.The users, passwords and permissions are defined in a file called /etc/asterisk/manager.conf The following represents a part of the file manager.conf that is distributed with Elastix by default. ;; AMI - Asterisk Manager interface;[general]enabled = yesport = 5038bindaddr = 0.0.0.0 [admin]secret = elastix456deny=0.0.0.0/0.0.0.0permit=127.0.0.1/255.255.255.0read =system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originatewrite =system,call,log,verbose,command,agent,user,config,command,dtmf,reporting,cdr,dialplan,originate #include manager_additional.conf#include manager_custom.conf

In this file, a user is defined, named admin with the elastix456 password that can connect from the IP 127.0.0.1 with a255.255.255.0 mask. After this, certain permissions are defined for this user.

Testing from telnet To test the AMI interaction, it is not necessary to have a sophisticated program. A simple way to do it is through the telnet program,available on any computer. Let us see an example executing this command from the Elastix server itself and assuming the above configuration file. First, we connect to the Elastix server through a telnet session. For this, we execute the following from the command line: [root@elastix ~]# telnet 127.0.0.1 5038Trying 127.0.0.1...Connected to localhost.localdomain (127.0.0.1).Escape character is '^]'.Asterisk Call Manager/1.1

As we can see, the server has answered us with a message indicating that AMI is listening and is telling us that it is using version

Page 467: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

1.1 of the protocol. Below we authenticate with the user name and password specified in the file manager.conf. We need to write the following inthe terminal. Action: LoginActionID: 1Username: adminSecret: elastix456

It is important to know that after writing the above command and sending it we must return twice. That is, we must press Enter twotimes to send the previous authentication petition. AMI will answer with a success or an error message after this. The following isthe message we get when it is successful. Response: SuccessActionID: 1Message: Authentication accepted

From now on, register messages that AMI will send to our session each time an event occurs will start to appear. For example, wewill receive messages when a call is ended or if an extension is ringing. Once the session is authenticated, we can perform commands, also known as actions, directly through AMI.

AMI packet types In AMI communication, there are three different types of information packets.

Action: A command sent by the AMI service client to be processed.Response: Asterisk’s response to the action required by the client.Event: The information of an asynchronous event that occurred in Asterisk. For example, the arrival of a telephone call.

To relate the responses with the actions an ActionID can be included with each action. Asterisk will return this parameter in theresponse.

AMI actions or commands The following AMI command listing is obtained when the command manager show commands is executed from the ElastixCLI. Command Privileges Description

AbsoluteTimeout system,call,all

Specifiesabsolutetimeout

AgentLogoff agent,all

Specifies thata user hasstopped beingauthenticated

Agents agent,all

Lists agentsand theirstatesAdds an AGIcommand forexecution

Page 468: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

AGI agi,allwith AsyncAGI

Atxfer call,allAttendedtransfer

Bridge call,all

Connects twochannelspresent in thePBX

Challenge <none>

Generates achallenge forMD5authentication

ChangeMonitor call,all

Changes themonitoringfile for achannel

Command command,all

Executes aCLIcommand

CoreSettings system,reporting,all

Shows thePBX coresettings(version, etc.)

CoreShowChannels system,reporting,all

Lists currentactivechannels

CoreStatus system,reporting,all

Shows statusvariables forthe PBX core

CreateConfig config,all

Creates anempty file intheconfigurationdirectory

DAHDIDialOffhook <none>

Dial on aDAHDIchannel whileit’s offhook

DAHDIDNDoff <none>

Changes thedo not disturb(DND) stateof theDAHDIchannel toOFF

DAHDIDNDon <none>

Changes thedo not disturb(DND) stateof theDAHDIchannel toON

DAHDIHangup <none>

Hangs up theDAHDIchannel

DAHDIRestart <none>

Completelyrestarts theDAHDIchannels(ends allcalls)

Page 469: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

DAHDIShowChannels <none>

Shows theDAHDIchannel state

DAHDITransfer <none>

Transfers aDAHDIchannel

DBDel system,all

Deletes aregister in thedatabase

DBDelTree system,all

Deletes a treein thedatabase

DBGet system,reporting,all

Obtains aregister fromthe database

DBPut system,all

Adds aregister to thedatabase

Events <none>

Controls theflow of anevent

ExtensionState call,reporting,all

Verifies thestate of anextension

GetConfig system,config,allObtains theconfiguration

GetConfigJSON system,config,all

Obtains theconfigurationin JSONformat

Getvar call,reporting,all

Obtains achannelvariable

Hangup system,call,allHangs up achannel

IAXnetstats system,reporting,all

Shows IAXnetworkstatistics

IAXpeerlist system,reporting,allLists IAXpeers

IAXpeers system,reporting,allLists IAXpeers

IAXregistry system,reporting,allShows IAXregistry

ListCategories config,all

Lists thecategories intheconfigurationfile

ListCommands <none>

Lists theavailablemanagercommands(AMI)

Login <none>

Starts aManagersessionEnds aManager

Page 470: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

Logoff <none> session

MailboxCount call,reporting,all

Checks thenumber ofmessages inthe inbox

MailboxStatus call,reporting,allChecks theinbox

MeetmeList reporting,all

Lists theparticipantsin aconference

MeetmeMute call,allMutes ameetme user

MeetmeUnmute call,allUnmutes ameetme user

ModuleCheck system,all

Verifies if amodule isloaded

ModuleLoad system,allLoads amodule

Monitor call,allMonitors achannel

Originate originate,allOriginates acall

Park call,allParks achannel

ParkedCalls <none>Lists parkedcalls

PauseMonitor call,all

Pauseschannelmonitoring

Ping <none>

Command tomaintain theconnectionactive

PlayDTMF call,all

Plays DTMFsignal in aspecificchannel

QueueAdd agent,all

Adds aninterface tothe queue

QueueLog agent,all

Adds apersonalizedrecord to thequeue log

QueuePause agent,all

Establishes amember of aqueue astemporarilyunavailable

QueuePenalty agent,all

Establishesthe penaltyfor a memberof a queueReloads aqueue,queues or anysubsection of

Page 471: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

QueueReload <none>a queue orqueues

QueueRemove agent,all

Deletes aninterfacefrom a queue

QueueReset <none>

Dumps thestatistics for aqueue

QueueRule <none> Queue rulesQueues <none> QueuesQueueStatus <none> Queue status

QueueSummary <none>Queuesummary

Redirect call,allTransfers acall

Reload system,config,allSends areload event

SendText call,all

Sends a textmessage tothe channel

Setvar call,all

Establishes achannelvariable

ShowDialPlan config,reporting,allShows thedial plan

SIPnotify system,allSends a SIPnotification

SIPpeers system,reporting,all

Lists SIPpeers (textformat)

SIPqualifypeer system,reporting,all

Shows SIPpeers (textformat)

SIPshowpeer system,reporting,all

Shows SIPpeers (textformat)

SIPshowregistry system,reporting,all

Shows SIPregistry (textformat)

Status system,call,reporting,allLists thechannel status

StopMonitor call,allStops channelmonitoring

UnpauseMonitor call,all

Unpauses achannelmonitor

UpdateConfig config,allUpdates basicconfiguration

UserEvent user,all

Sends anarbitraryevent

VoicemailUsersList call,reporting,all

Lists all theinformationfor voicemailusers

WaitEvent <none>

Waits for anevent tooccur

Page 472: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/chapter_16/16.2_Asterisk_AMI.htm[24/11/2011 10:25:22 p.m.]

Previous Go to Index Next

Page 473: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

Previous Go to Index

AAsterisk configuration files distributedwith Elastix File Descriptiona2billing.conf General configuration file for a2billingadditional_a2billing_iax.conf IAX configuration for a2billingadditional_a2billing_sip.conf SIP configuration for a2billingadsi.conf ADSI configuration file (Analog Display

services Interface.) With ADSI Asterisk caninteract with the analog telephones’ display.

adtranvofr.conf Configuration file that allows voice supporton Frame Relay

agents.conf Configuration file that allows managing ofagents in queues.

alarmreceiver.conf Serves to configure the applicationAlarmReciever().

alsa.conf Configures the sound driver for the ALSAdrivers

amd.conf Used for automatic detection of answeringmachines

applications.conf Basically includes the dial plan. Thecontexts included here can be calledapplications and their name starts with thechain “app-“.

asterisk.conf Main configuration file for Asterisk. Hereare configured the work directories forAsterisk as well las some general options.

cbmysql.conf Configuration file for the Asterisk module

Page 474: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

CBMySQL (Conference Bridge MySQL)used to manage conferences in Elastix.

cdr.conf Main configuration file for CDR reportingcdr_custom.conf This file defines what is written in Asterisk

CDRs.cdr_manager.conf This file controls whether CDRs are sent

through AMI (Asterisk Manager Interface).cdr_mysql.conf Configuration file for the module cdr_mysql

that allows registering CDRs in the MySQLdatabase.

cdr_odbc.conf Here the module that allows registeringCDRs through the ODBC driver of thedatabase is configured

cdr_pgsql.conf Here the module that allows registeringCDRs in the PostgreSQL database isconfigured.

cdr_tds.conf With this file we can configure the modulethat allows registration of CDRs throughfreeTDS drivers. For example, with thismodule we can register CDRs in the MS-SQL database.

chan_dahdi.conf This file contains the DADHI-type channelconfiguration. This file also includes thefiles chan_dahdi_additional.confand dahdi-channels.conf.

chan_dahdi_additional.conf This file is overwritten by FreePBX mainlywhen DAHDI-type extensions are created.

cli.conf Configuration file for the Asterisk console.codecs.conf In this file some options are configured that

control the operation of some codecs.dahdi-channels.conf This file is included in

chan_dahdi.conf and is anautomatically generated file by the ElastixHardware Detector through the tooldahdi_genconf.

dnsmgr.conf This file defines whether Asterisk shouldrealize regular DNS petitions and howoften.

dundi.conf DUNDI configuration file (DistributedUniversal Number Discovery).

enum.conf ENUM configuration fileextconfig.conf Allows configuration of what is known as

“external configuration.” Basically afunctionality that allows mapping anyconfiguration file with an external entity,like a database.

extensions.ael Dial plan in AEL format (AsteriskExtension Language). Not used in Elastix

extensions.conf Configuration file that includesextensions_additional.conf andextensions_custom.conf.

Page 475: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

extensions_a2billing.conf Additional dial plan for the applicationA2Billing

extensions_additional.conf Asterisk configuration file modified forFreePBX that should not be edited by handbecause all changes are lost

extensions_custom.conf File where personalized contexts forAsterisk can be created without FreePBXoverwriting them.

features.conf Here some Asterisk features can beconfigured, like transfer parameters and callcapture.

features_applicationmap_additional.conf File included in features.conf thatcontains the configuration of theapplicationmap section and that isoverwritten by FreePBX

features_applicationmap_custom.conf File included in features.conf thatcontains the configuration of theapplicationmap section and that canbe modified by the user since it’s notoverwritten by FreePBX

features_featuremap_additional.conf File included in features.conf thatcontains elements of configuration of the featuremap section and that isoverwritten by FreePBX

features_featuremap_custom.conf File included in features.conf thatcontains the configuration of thefeaturemap section and thatcan be modified by the usersince it isn’t overwritten byFreePBX.

features_general_additional.conf General features configuration file that isoverwritten by FreePBX

features_general_custom.conf General features configuration file that canbe modified by the user because FreePBXdoesn’t overwrite it.

festival.conf Festival configuration file.followme.conf Configuration for the followme

functionalityfunc_odbc.conf Allows configuring connection parameters

in a database through the ODBC driver tomake fast queries through the same dialplan.

globals_custom.conf Allos the user to define global variables thatwon’t be overwritten by FreePBX. This fileis included inextensions_additional.conf.

gtalk.conf Configuration file so that Asterisk work as aclient for the service Google Talk.

h323.conf Configuration file for the H.323 protocolaccording to the implementiation baes onProject open H.323. There are otherimplementations.

http.conf Configuration for the mini web server

Page 476: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

embedded in Asterisk. By default thisservice is turned off so one should becareful not to lift it in the same port as theApache server that is integrated in Elastix.

iax.conf Main IAX file that includes the others.iax_additional.conf IAX configuration generated by FreePBX

that shouldn’t be editediax_custom.conf IAX configuration that can be edited since

it’s not overwritten by FreePBXiax_general_additional.conf File complementary to iax.conf where

FreePBX writes general configuration. Thisis because now the file iax.conf is simply aninclusion file, in other words that it includesother file

iax_general_custom.conf Similar toiax_general_additional.conf buthere the user can write FreePBX doesn’toverwrite information since this file.

iax_registrations_custom.conf Similar to iax_registrations.confbut this file isn’t overwritten by FreePBX,allowing it to store user configurationwithout it being written over.

iax_registrations.conf File used by FreePBX to store registry chaininformation with other PBXs or VoIPproviders that use IAX protocol.

iaxprov.conf File used to update the IAX devices’firmware

indications.conf File to configure tone definition. Thesetones can vary from one country to the nextor from one telephone company to the next.

jabber.conf File that allows configuration of XMPPsupport in Asterisk. This is because Asteriskcan connect as a client to a XMPP server.(The name Jabber is the previous name forXMPP protocol.)

jingle.con Jingle configuration file. Jingle is anextension of XMPP protocol that allowssupporting multimedia through thisprotocol.

localprefixes.conf File that allows to configure dialing rulesbased on prefixes.

logger.conf In this file Asterisk logging can beconfigured. See the diagnostics section formore information.

manager.conf Configuration file for the Asterisk ManagerInterface service.

manager_additional.conf AMI configuration information that can beoverwritten by FreePBX.

manager_custom.conf Configuration information for AMI for useraccess, since this file isn’t overwritten byFreePBX.

meetme.conf Configuration of permanent conference

Page 477: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

rooms.meetme_additional.conf Configuration for written conference rooms

for FreePBX.mgcp.conf Configuration of MGCP protocolmisdn.conf Configuration file for the chan_misdn

channel in Asteriskmodem.conf Configuration file for modem and ISDN

support using ISDN4Linux or CAPI4Linuxdrivers.

modules.conf This file tells Asterisk which modules toload and which not to load.

musiconhold.conf Here the waiting music is configured.Asterisk is very flexible and even supportsaudio streaming.

musiconhold_additional.conf Configuration file for waiting music,overwritten by FreePBX.

musiconhold_custom.conf Waiting music definition defined by theuser. This file isn’t overwritten byFreePBX.

muted.conf Allows sensing audio to certain channelsand reducing the volume for those channelswhile they are active.

osp.conf Allows configuration for OSP protocol(Open Settlement Protocol). This protocolallows us to interchange information (likeaccounting and use) with providers thatsupport that protocol.

oss.conf Allows configuration for OSS (Open SoundSystem) channels. OSS is an audio driver(or a group of audio drivers) and allows usto configure channels in the sound carditself. Something similar to the ALSA report.

parking_additional.inc File the stores certain parking lotinformation. This file is automaticallywritten by the module Parkinglot.

phone.conf Allows configuring phone-type channelsthat are based on a project Linux channelimplementation, or Linux Telephony thatsupports these kinds of Linux devices.

phpagi.conf Configures some basic parameters for thesupport of PHPAGI library

privacy.conf Basically this file defines the number oftries that a user has to try to enter a validtelephone number into the applicationPrivacyManager().

queues.conf General configuration file for queues. If onewishes to edit queues in a text file it’srecommended to modifyqueues_custom.conf.

Page 478: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

queues_additional.conf File that creates queues generated fromFreePBX. Should not be manually modifiedbecause changes may be lost.

queues_custom_general.conf General queue configuration file written bythe user, that is, it’s not written over byFreePBX.

queues_custom.conf Queue configuration file that can bemodified by users without being deleted byFreePBX.

queues_general_additional.conf General queue configuration file written byFreePBX.

queues_post_custom.conf FreePBX does not use this file now.res_mysql.conf Allows Asterisk to obtain the configuration

of the MySQL database. This concept isnamed Asterisk Realtime.

res_odbc.conf Allows Asterisk to obtain the configurationfor databases through the ODBC driver.

res_pgsql.conf Allows Asterisk to obtain the configurationof the PostgreSQL database.

res_snmp.conf Allows SNMP support configuration inAsterisk

rpt.conf Radio repeater configuration file. Thisallows Asterisk to communicate throughVoIP using radio repetition technology.

rtp.conf RTP protocol configuration. Here the rangeof RTP ports used by Asterisk can beconfigured.

say.conf Defines certain internationalizationparameters.

sip.conf SIP configuration file that includes theothers.

sip_additional.conf SIP configuration generated by FreePBXand that should not be edited manually.

sip_custom.conf SIP configuration that can be modified andis not overwritten by FreePBX.

sip_general_additional.conf Complementary file to sip.conf whereFreePBX writes general configuration. Thisis because now the file sip.conf is leftas a simple inclusion file, that is it includesother files.

sip_general_custom.conf Similar tosip_general_additional.conf buthere the user can write information into thefile, since this file isn’t overwritten byFreePBX

sip_nat.conf Configuration for working with SIP througha NAT (Network Address Translation).

sip_notify.conf Used to configure the support that allows toremotely restart some SIP phones.

sip_registrations_custom.conf Similar to sip_registrations.confbut this file isn’t overwritten by FreePBX

Page 479: Comunicaciones Unificadas Con Elastix Vol. 1

Unified Communications with Elastix Vol. 1

http://www.elastixbook.com/en/chapters/Appendix.htm[24/11/2011 10:25:23 p.m.]

allowing it to store user configurationwithout worrying about it being deleted

sip_registrations.conf File used by FreePBX for storing registrychain information with other PBXs or VoIPproviders.

skinny.conf Allows configuration of the SCCP protocol(Skinny Client Control Protocol) inAsterisk.

sla.conf Configuration of SLAs (Shared LineAppearances).

smdi.conf Allows SMDI support configuration(Station Message Desk Interface) thatallows Asterisk to function as a voicemailsystem for PBXs that support this protocol.

udptl.conf Allows Asterisk to support UDPTL packets.These packets are used for protocol T.38 forfax.

unicall.conf Here the module chan_unicall isconfigured.

users.conf This file is used to define the concept of“user” that can have optionally associated atelephone (or extension.) This models betterthe fact that one same user can changetelephone device and that from any devicehe is able to authenticate.

vm_email.inc Email template that is sent to notify the userof the arrival of a voicemail.

vm_general.inc Some general parameters related tovoicemail.

voicemail.conf Configuration file for voice mail.vpb.conf Configuration file for VoiceTronix cards.

The following group of files can be found in versions of Elastix below 2.9, when Zaptel drivers were still used.They are listed here as reference. File Descriptionzapata_additional.conf File that FreePBX overwrites and that is

included in zapata.conf. Used mainlywhen creating ZAP-type extensions.

zapata-channels.conf File written by the script genzaptelconfand by the Elastix hardware detector to addconfiguration to zapata.conf.

zapata.conf Configuration for telephony cards that useZaptel drivers.

Previous Go to Index