Exemplo n.º 1
0
        public bool Connect()
        {
            if (String.IsNullOrEmpty(Login) || String.IsNullOrEmpty(Address))
            {
                throw new ArgumentException("Не верны данные для подключения, проверте логин, пароль, адрес и порт!");
            }

            if (_connection != null)
            {
                if (_connection.IsConnected())
                {
                    _connection.Logoff();
                }
            }
            else
            {
                _connection = new ManagerConnection();
                _connection.FireAllEvents   = true;
                _connection.UnhandledEvent += _connection_UnhandledEvent;
                //_connection.Dial += _connection_Event_Dial; ;
                //_connection.Bridge += _connection_Event_Bridge;
                //_connection.Hangup += _connection_Event_Hangup;
            }

            _connection.Username = Login;
            _connection.Password = Password;
            _connection.Hostname = Address;
            _connection.Port     = Port;

            _connection.Login();

            return(_connection.IsConnected());
        }
Exemplo n.º 2
0
        private static void checkManagerAPI()
        {
            manager = new ManagerConnection(ASTERISK_HOST, ASTERISK_PORT, ASTERISK_LOGINNAME, ASTERISK_LOGINPWD);

            manager.NewState += new NewStateEventHandler(dam_NewStateEvent);

            manager.Dial += new DialEventHandler(dam_Dial);



            manager.PingInterval = 0;
            // +++
            try
            {
                manager.Login();                        // Login only (fast)

                Console.WriteLine("Asterisk version : " + manager.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
                manager.Logoff();
                return;
            }

            Console.ReadLine();

            manager.Logoff();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            manager = new ManagerConnection(ASTERISK_HOST, ASTERISK_PORT, ASTERISK_LOGINNAME, ASTERISK_LOGINPWD);

            manager.PingInterval = 0;
            // +++
            try
            {
                manager.Login();                        // Login only (fast)

                Console.WriteLine("Asterisk version : " + manager.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
                manager.Logoff();
                return;
            }

            if (args.Count() == 4)
            {
                string originateChannel  = args[0];
                string originateCallerId = args[1];
                string originateExten    = args[2];
                string originateContext  = args[3];
                //string originateChannel = "SIP/billy";
                //string originateCallerId = "<1001>";
                //string originateExten = "1002";
                //string originateContext = "phones";

                OriginateAction oc = new OriginateAction();

                //oc.Channel = originateChannel;
                //oc.CallerId = originateCallerId;
                //oc.Context = originateContext;
                //oc.Exten = originateExten;
                //oc.Priority = 2;
                //oc.Timeout = 15000;

                oc.Channel     = originateChannel;
                oc.CallerId    = originateCallerId;
                oc.Application = "Dial";
                oc.Data        = "Local/" + originateExten + "@" + originateContext;
                oc.Timeout     = 15000;

                try
                {
                    ManagerResponse originateResponse = manager.SendAction(oc, oc.Timeout);
                }
                catch (Exception e)
                {
                    Console.WriteLine("error: {0}", e.Message);
                }
            }
            manager.Logoff();
        }
Exemplo n.º 4
0
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AstCon.Logoff();
            AstCon = null;

            Application.Exit();
        }
Exemplo n.º 5
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string address  = this.tbAddress.Text;
            int    port     = int.Parse(this.tbPort.Text);
            string user     = this.tbUser.Text;
            string password = this.tbPassword.Text;

            btnConnect.Enabled      = false;
            manager                 = new ManagerConnection(address, port, user, password);
            manager.UnhandledEvent += new ManagerEventHandler(manager_Events);
            try
            {
                // Uncomment next 2 line comments to Disable timeout (debug mode)
                // manager.DefaultResponseTimeout = 0;
                // manager.DefaultEventTimeout = 0;
                manager.Login();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error connect\n" + ex.Message);
                manager.Logoff();
                this.Close();
            }
            btnDisconnect.Enabled = true;
        }
Exemplo n.º 6
0
        //-------------------------------------------------------------------------------------------------------------

        void OKbuttonClick(object sender, EventArgs e)
        {
            if ((manager != null) && (manager.IsConnected() == true))
            {
                manager.Logoff();
            }
            this.Close();
        }
Exemplo n.º 7
0
 private void btnDisconnect_Click(object sender, EventArgs e)
 {
     btnConnect.Enabled = true;
     if (this.manager != null)
     {
         manager.Logoff();
         this.manager = null;
     }
     btnDisconnect.Enabled = false;
 }
Exemplo n.º 8
0
 protected override void OnStop()
 {
     log.Debug("Stopping AsteriskConnector...");
     try
     {
         foreach (LineControl l in linecontrols)
         {
             l.status = Status.unknown;
             l.lineControlConnection = null;
             ss.SetLineControl(l);
         }
         manager.Logoff();
     }
     catch (Exception e)
     {
         log.Debug("Exception while stopping AsteriskConnector: " + e.Message);
     }
 }
Exemplo n.º 9
0
        //-------------------------------------------------------------------------------------------------------------

        private void NewCallerQForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tmr_call_time != null)
            {
                tmr_call_time.Stop();
                tmr_call_time.Dispose();
            }

            if (nf != null)
            {
                if ((manager != null) && (manager.IsConnected() == true))
                {
                    manager.Logoff();
                }

                nf.Close();
                nf.Dispose();
            }
        }
Exemplo n.º 10
0
 private void ConnectionStateIndicatorDoubleClick(object sender, EventArgs e)
 {
     if (_autoPollPaused)
     {
         autoPollTimer.Start();
         _autoPollPaused = false;
         LogToConsole("Automatic polling started.", ConsoleTextColor.Info);
     }
     else
     {
         autoPollTimer.Stop();
         _autoPollPaused = true;
         LogToConsole("Automatic polling paused. Please double click connection state indicator to unpause.", ConsoleTextColor.Info);
         if (managerConnection.IsConnected())
         {
             managerConnection.Logoff();
             LogToConsole("Disconnected.", ConsoleTextColor.Info);
         }
         UpdateConnectionStateIndicator();
     }
 }
Exemplo n.º 11
0
        private void llamar_Click(object sender, EventArgs e)
        {
            connectToAsterisk();
            registros.Clear();
            registros.Text  = "--- Conexion Exitosa : ) --- " + Environment.NewLine;;
            registros.Text += "** Generando LLAMADA **" + Environment.NewLine;
            //registros.Text += "Al Numero: " + telefono.Text + " Desde la Extension: " + extension.Text + Environment.NewLine;

            var originateAction   = new OriginateAction();
            var originateResponse = new ManagerResponse();

            //originateAction.Channel = "Local/201@from-internal"; //Local/210@from-internal
            originateAction.Channel  = "local/" + telefono.Text + "@from-internal"; //SIP/actionvoip/0085261234567,Ttr
            originateAction.CallerId = telefono.Text;
            originateAction.Context  = "from-internal";                             //from-internal,
            originateAction.Exten    = extension.Text;
            //originateAction.Application = "Dial";
            //originateAction.Data = "SIP/210,201,Ttr"; //SIP/210,201,Ttr
            originateAction.Priority = 1;
            originateAction.Timeout  = 30000;
            //originateAction.Async = true;

            // Realizando Login en el Servidor
            connectToAsterisk();



            registros.Text += "Llamado a Telefono: " + telefono.Text + Environment.NewLine;
            registros.Text += "Esperando a que Contesten: ";

            // Enviando Parametros para generar llamada, timbrara por 30 sg en el cliente, cuando contesten envia al agente
            originateResponse = asteriskManager.SendAction(originateAction, originateAction.Timeout);
            registros.Text   += originateResponse.Response + Environment.NewLine;
            Debug.WriteLine(originateResponse.Response);
            registros.Text += "Llamando al Agente : " + extension.Text + Environment.NewLine;

            //  Desconectando del Servidor
            asteriskManager.Logoff();
        }
Exemplo n.º 12
0
        private void connectToAsterisk()
        {
            try
            {
                // Conexion al Servidor Asterisk
                //asteriskManager = new ManagerConnection("192.168.10.200", 5038, "johan", "johan");  // Server Pruebas
                asteriskManager = new ManagerConnection("10.0.0.75", 5038, "ccempaques", "ccempaques"); // Server Empaques
                asteriskManager.UnhandledEvent += new ManagerEventHandler(asteriskManager_Events);

                // Login con --> Objeto astriskManager
                asteriskManager.Login();
            }
            // Conexion Falla
            catch (Exception ex)
            {
                MessageBox.Show("NO ME HE CONECTADO AL SERVIDOR ASTERISK.\n\n" + ex.ToString(),
                                "Error en la Conexion AMI",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
                asteriskManager.Logoff();
                this.Close();
            }
        }
Exemplo n.º 13
0
        private static void checkManagerAPI()
        {
            manager = new ManagerConnection(ASTERISK_HOST, ASTERISK_PORT, ASTERISK_LOGINNAME, ASTERISK_LOGINPWD);

            // Register user event class
            manager.RegisterUserEventClass(typeof(UserAgentLoginEvent));

            // Add or Remove events
            manager.UserEvents += new UserEventHandler(dam_UserEvents);

            // Dont't display this event
            manager.NewExten += new NewExtenEventHandler(manager_IgnoreEvent);

            // Display all other
            manager.UnhandledEvent += new ManagerEventHandler(dam_Events);

            // +++ Only to debug purpose
            manager.FireAllEvents = true;
            // manager.DefaultEventTimeout = 0;
            // manager.DefaultResponseTimeout = 0;
            manager.PingInterval = 0;
            // +++
            try
            {
                manager.Login();                                        // Login only (fast)

                Console.WriteLine("Asterisk version : " + manager.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
                manager.Logoff();
                return;
            }

            {
                Console.WriteLine("\nGetConfig action");
                ManagerResponse response = manager.SendAction(new GetConfigAction("manager.conf"));
                if (response.IsSuccess())
                {
                    GetConfigResponse responseConfig = (GetConfigResponse)response;
                    foreach (int key in responseConfig.Categories.Keys)
                    {
                        Console.WriteLine(string.Format("{0}:{1}", key, responseConfig.Categories[key]));
                        foreach (int keyLine in responseConfig.Lines(key).Keys)
                        {
                            Console.WriteLine(string.Format("\t{0}:{1}", keyLine, responseConfig.Lines(key)[keyLine]));
                        }
                    }
                }
                else
                {
                    Console.WriteLine(response);
                }
            }

            {
                Console.WriteLine("\nUpdateConfig action");
                UpdateConfigAction config = new UpdateConfigAction("manager.conf", "manager.conf");
                config.AddCommand(UpdateConfigAction.ACTION_NEWCAT, "testadmin");
                config.AddCommand(UpdateConfigAction.ACTION_APPEND, "testadmin", "secret", "blabla");
                ManagerResponse response = manager.SendAction(config);
                Console.WriteLine(response);
            }

            // Originate call example
            Console.WriteLine("\nPress ENTER key to originate call.\n"
                              + "Start phone (or connect) or make a call to see events.\n"
                              + "After all events press a key to originate call.");
            Console.ReadLine();

            OriginateAction oc = new OriginateAction();

            oc.Context  = ORIGINATE_CONTEXT;
            oc.Priority = "1";
            oc.Channel  = ORIGINATE_CHANNEL;
            oc.CallerId = ORIGINATE_CALLERID;
            oc.Exten    = ORIGINATE_EXTEN;
            oc.Timeout  = ORIGINATE_TIMEOUT;
            // oc.Variable = "VAR1=abc|VAR2=def";
            // oc.SetVariable("VAR3", "ghi");
            ManagerResponse originateResponse = manager.SendAction(oc, oc.Timeout);

            Console.WriteLine("Response:");
            Console.WriteLine(originateResponse);

            Console.WriteLine("Press ENTER key to next test.");
            Console.ReadLine();

            //
            // Display result of Show Queues command
            //
            {
                CommandAction   command  = new CommandAction();
                CommandResponse response = new CommandResponse();
                if (manager.AsteriskVersion == AsteriskVersion.ASTERISK_1_6)
                {
                    command.Command = "queue show";
                }
                else
                {
                    command.Command = "show queues";
                }
                try
                {
                    response = (CommandResponse)manager.SendAction(command);
                    Console.WriteLine("Result of " + command.Command);
                    foreach (string str in response.Result)
                    {
                        Console.WriteLine("\t" + str);
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine("Response error: " + err);
                }
                Console.WriteLine("Press ENTER to next test or CTRL-C to exit.");
                Console.ReadLine();
            }
            //
            // Display Queues and Members
            //
            ResponseEvents re;

            try
            {
                re = manager.SendEventGeneratingAction(new QueueStatusAction());
            }
            catch (EventTimeoutException e)
            {
                // this happens with Asterisk 1.0.x as it doesn't send a QueueStatusCompleteEvent
                re = e.PartialResult;
            }

            foreach (ManagerEvent e in re.Events)
            {
                if (e is QueueParamsEvent)
                {
                    QueueParamsEvent qe = (QueueParamsEvent)e;
                    Console.WriteLine("QueueParamsEvent" + "\n\tQueue:\t\t" + qe.Queue + "\n\tServiceLevel:\t" + qe.ServiceLevel);
                }
                else if (e is QueueMemberEvent)
                {
                    QueueMemberEvent qme = (QueueMemberEvent)e;
                    Console.WriteLine("QueueMemberEvent" + "\n\tQueue:\t\t" + qme.Queue + "\n\tLocation:\t" + qme.Location);
                }
                else if (e is QueueEntryEvent)
                {
                    QueueEntryEvent qee = (QueueEntryEvent)e;
                    Console.WriteLine("QueueEntryEvent" + "\n\tQueue:\t\t" + qee.Queue + "\n\tChannel:\t" + qee.Channel + "\n\tPosition:\t" + qee.Position);
                }
            }

            Console.WriteLine("Press ENTER to next test or CTRL-C to exit.");
            Console.ReadLine();

            //
            //	To test create 3 extensions:
            //	1 - SIP/4012 w/o voicemail (with eyeBeam softphone)
            //	2 - IAX2/4008 w/o voicemail (with iaxComm softphone)
            //	3 - SIP/4010 w/ voicemal but no phone connect

            //	RedirectCall: call from IAX2/4008 to SIP/4012
            //	Don't answer on SIP/4012 and call must redirect to SIP/4010 (to voicemail really)
            //	Dial event used to define redirect channel

            Console.WriteLine("Redirect Call from " + ORIGINATE_CHANNEL + " to " + ORIGINATE_EXTRA_CHANNEL + " or press ESC.");
            // Wait for Dial Event from ORIGINATE_CHANNEL
            DialEventHandler de = new DialEventHandler(dam_Dial);

            manager.Dial += de;
            while (transferChannel == null)
            {
                System.Threading.Thread.Sleep(100);
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
                {
                    break;
                }
            }
            manager.Dial -= de;

            // Now send Redirect action
            RedirectAction ra = new RedirectAction();

            ra.Channel      = transferChannel;
            ra.ExtraChannel = ORIGINATE_EXTRA_CHANNEL;
            ra.Context      = ORIGINATE_CONTEXT;
            ra.Exten        = ORIGINATE_EXTRA_EXTEN;
            ra.Priority     = 1;
            try
            {
                ManagerResponse mr = manager.SendAction(ra, 10000);
                Console.WriteLine("Transfer Call"
                                  + "\n\tResponse:" + mr.Response
                                  + "\n\tMessage:" + mr.Message
                                  );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //	Monitor call.
            //	Call from IA2/4008 to SIP/4012
            //	Link event used to define monitor channel
            Console.WriteLine("Monitor call. Please call " + ORIGINATE_CHANNEL + " and answer or press ESC.");
            // Wait for Link event
            LinkEventHandler le = new LinkEventHandler(dam_Link);

            manager.Link += le;
            while (monitorChannel == null)
            {
                System.Threading.Thread.Sleep(100);
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
                {
                    break;
                }
            }
            manager.Link -= le;
            // Now send Monitor action
            MonitorAction ma = new MonitorAction();

            ma.Channel = monitorChannel;
            ma.File    = "voicefile";
            ma.Format  = "gsm";
            ma.Mix     = true;
            try
            {
                ManagerResponse mr = manager.SendAction(ma, 10000);
                Console.WriteLine("Monitor Call"
                                  + "\n\tResponse:" + mr.Response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            manager.Logoff();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Quay số gọi ra  - tổng đài ip
        /// </summary>
        private bool QuaySoGoiDien()
        {
            bool         bRet = false;
            const string ORIGINATE_CONTEXT = "from-internal";

            if (G_manager == null)
            {
                return(false);
            }
            try
            {
                if (!G_manager.IsConnected())
                {
                    G_manager = new ManagerConnection(AsteriskInfo.AST_HOSTNAME, AsteriskInfo.AST_PORT_NUMBER, AsteriskInfo.AST_USERNAME, AsteriskInfo.AST_PASSWORD);

                    LogError.WriteLogInfo("ReConnected:" + G_PhoneNumber);
                }
                if (G_manager.IsConnected())
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thành công";
                    }));
                }
                else
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thất bại !!!";
                    }));
                }
                G_manager.Login();
                var oc = new OriginateAction()
                {
                    Context  = ORIGINATE_CONTEXT,
                    Priority = 1,
                    Channel  = "SIP/" + G_lineIPPBX,
                    CallerId = G_lineIPPBX,
                    Exten    = G_PhoneNumber,
                    Timeout  = 5000,
                    //Async = true
                };
                if (G_manager.SendAction(oc).IsSuccess())
                {
                    bRet = true;
                }
                else
                {
                    bRet = false;
                }

                G_manager.Logoff();
            }
            catch (Exception ex)
            {
                //bw_Call.CancelAsync();
                bRet = false;
                G_manager.Logoff();
                LogError.WriteLogError("QuaySoGoiDien2", ex);
            }
            return(bRet);
        }
Exemplo n.º 15
0
        private bool QuaySoGoiDien(ManagerConnection manager, string line, string phoneNumber)
        {
            bool         bRet = false;
            const string ORIGINATE_CONTEXT = "from-internal";

            if (manager == null)
            {
                return(false);
            }
            try
            {
                G_manager = manager;
                string channel = string.Format("{0}/{1}", Config_Common.ChannelDial, line);
                if (!G_manager.IsConnected())
                {
                    G_manager = new ManagerConnection(AsteriskInfo.AST_HOSTNAME, AsteriskInfo.AST_PORT_NUMBER, AsteriskInfo.AST_USERNAME, AsteriskInfo.AST_PASSWORD);
                }
                G_manager.Login();
                if (G_manager.IsConnected())
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thành công - " + channel;
                    }));
                }
                else
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thất bại !!! - " + channel;
                    }));
                }
                OriginateAction oc = new OriginateAction()
                {
                    Context  = ORIGINATE_CONTEXT,
                    Priority = 1,
                    Channel  = channel,
                    CallerId = line,
                    Exten    = phoneNumber,
                    Timeout  = 15000
                };

                ManagerResponse originateResponse = G_manager.SendAction(oc, 30000);
                if (originateResponse.IsSuccess())
                {
                    bRet = true;
                }
                else
                {
                    bRet = false;
                }
                G_manager.Logoff();
            }
            catch (Exception ex)
            {
                bRet = false;
                G_manager.Logoff();
                LogError.WriteLogError("QuaySoGoiDien2", ex);
            }
            return(bRet);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Quay số gọi ra  - tổng đài ip
        /// </summary>
        private bool QuaySoGoiDien()
        {
            bool         bRet = false;
            const string ORIGINATE_CONTEXT = "from-internal";

            if (G_manager == null)
            {
                return(false);
            }
            try
            {
                string channel = string.Format("{0}/{1}", Config_Common.ChannelDial, G_lineIPPBX);
                if (!G_manager.IsConnected())
                {
                    G_manager = new ManagerConnection(AsteriskInfo.AST_HOSTNAME, AsteriskInfo.AST_PORT_NUMBER, AsteriskInfo.AST_USERNAME, AsteriskInfo.AST_PASSWORD);

                    LogError.WriteLogInfo("ReConnected:" + G_PhoneNumber);
                }
                G_manager.Login();
                if (G_manager.IsConnected())
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thành công - " + channel;
                    }));
                }
                else
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        Text = "Gọi đi : Kết nối tổng đài IP thất bại !!! - " + channel;
                    }));
                }
                var oc = new OriginateAction()
                {
                    Context  = ORIGINATE_CONTEXT,
                    Priority = 1,
                    Channel  = channel,//"SIP/" + G_lineIPPBX,
                    CallerId = G_lineIPPBX,
                    Exten    = G_PhoneNumber + Config_Common.Asterisk_SetNumberSign,
                    Timeout  = Config_Common.Asterisk_CallOut_TimeOut,
                    //Async = true
                };
                //oc.SetVariable("exten", G_PhoneNumber);
                if (G_manager.SendAction(oc, oc.Timeout).IsSuccess())
                {
                    bRet = true;
                }
                else
                {
                    bRet = false;
                }

                G_manager.Logoff();
            }
            catch (Exception ex)
            {
                //bw_Call.CancelAsync();
                bRet = false;
                G_manager.Logoff();
                LogError.WriteLogError("QuaySoGoiDien2", ex);
            }
            return(bRet);
        }