Example #1
0
        public String Monitorear(String Canal)
        {
            MonitorAction   mo        = new MonitorAction(Canal, UniqueId, "gsm", true);
            ManagerResponse response2 = Conn.SendAction(mo, 15000);

            return(response2.Message);
        }
        public void CallStart(string originate_channel, string originate_callerid, string originate_exten)
        {
            if (!manager.IsConnected())
            {
                throw new AsteriskNotConnectedException("Asterisk not connected. Contact with administrator");
            }

            try
            {
                OriginateResponseEvent a = new OriginateResponseEvent(manager);
                Console.WriteLine(a.Exten);

                OriginateAction oc = new OriginateAction();
                oc.Context  = options.OriginateContext;
                oc.Priority = "1";
                oc.Channel  = originate_channel;
                oc.CallerId = originate_callerid;
                oc.Exten    = originate_exten;
                oc.Timeout  = options.OriginateTimeout;
                oc.Async    = true;
                oc.ActionCompleteEventClass();
                // oc.Variable = "VAR1=abc|VAR2=def";
                //oc.SetVariable("VAR3", "ghi");
                ManagerResponse originateResponse = manager.SendAction(oc, oc.Timeout);
                Console.WriteLine(originateResponse);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #3
0
        public static ChannelData TakeChannel(ManagerConnection ami, int login, bool incoming = false, string outgoing = null)
        {
            var res = ChannelData.FirstOrDefault(c => c.Channel.Contains(login.ToString()));

            if (res != null)
            {
                ChannelData.Remove(res);
                return(res);
            }
            else
            {
                CommandAction coreShowChannels = new CommandAction()
                {
                    Command = "core show channels"
                };
                var         channels  = (CommandResponse)ami.SendAction(coreShowChannels, 10000);
                ChannelData manualRes = new ChannelData();
                channels.Result.Dump();
                // Get a string for the channel, works for both itnernal and external numbers
                string channelLine = channels.Result.FirstOrDefault(c => c.Contains("SIP/bbs") && c.Contains("AppDial((Outgoing Line))"))
                                     ?? channels.Result.FirstOrDefault(c => c.Contains("SIP/bbs") && c.Contains($"{PABX.CurrentUser.login}@bbs-pabx") && c.Contains($"Dial(SIP/{PABX.CurrentUser.login}"))
                                     ?? channels.Result.FirstOrDefault(c => c.Contains(outgoing));
                try
                {
                    manualRes.Channel = channelLine.Split(' ')[0];
                }
                catch (Exception e)
                {
                    e.Warn();
                }
                return(manualRes);
            }
        }
Example #4
0
        //-------------------------------------------------------------------------------------------------------------

        void TransferCall(string DialedNumber)
        {
            if (RINGENABLED != false)
            {
                // Now send Redirect action
                RedirectAction ra = new RedirectAction();
                ra.Channel = AsteriskPhoneAgentForm.CHANNEL_REMOTE;
                //ra.ExtraChannel = AsteriskPhoneAgentForm.;
                ra.Context  = ORIGINATE_CONTEXT;
                ra.Exten    = DialedNumber;
                ra.Priority = 1;
                try
                {
                    ManagerResponse mr = manager.SendAction(ra, 10000);
                    Log("Transfer Call"
                        + "\n\tResponse:" + mr.Response
                        + "\n\tMessage:" + mr.Message
                        );
                }
                catch (Exception ex)
                {
                    Log(ex.Message);
                }
            }
        }
Example #5
0
        public static void OriginarLigacao(string quemLiga, string quemAtende)
        {
            try
            {
                _manager.Login();

                var ramalOriginario  = quemLiga;
                var canalParaLigacao = quemAtende;

                var actionLigacao = new OriginateAction
                {
                    Context  = "default",                 //"from-internal",
                    Priority = "1",
                    Channel  = $"SIP/{canalParaLigacao}", //SIP/peer/9001
                    CallerId = "Chapeleta de Ouro",
                    Exten    = ramalOriginario,
                    Timeout  = 15000,
                    Async    = true
                };

                var originateResponse = _manager.SendAction(actionLigacao, actionLigacao.Timeout);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #6
0
 /// <summary>
 /// Generate a collection of parking data
 /// </summary>
 public static IEnumerable <ParkingSpot> PullParkingData(ManagerConnection ami)
 {
     for (int i = 701; i < 706; i++)
     {
         ExtensionStateAction action = new ExtensionStateAction()
         {
             Exten    = i.ToString(),
             Context  = "blf",
             ActionId = "1"
         };
         ExtensionStateResponse res = null;
         try
         {
             res = (ExtensionStateResponse)ami.SendAction(action);
         }
         catch (Exception e)
         {
             e.Warn();
         }
         if (res != null)
         {
             yield return new ParkingSpot(i.ToString())
                    {
                        InUse = res.Status == 1
                    }
         }
         ;
     }
 }
        public IActionResult Index()
        {
            manager.Login();
            ManagerResponse          response  = manager.SendAction(new GetConfigAction("manager.conf"));
            List <GetConfigResponse> getConfig = new List <GetConfigResponse>();

            if (response.IsSuccess())
            {
                GetConfigResponse responseConfig = (GetConfigResponse)response;
                getConfig.Add(responseConfig);
                return(View(getConfig));
            }
            else
            {
                Console.WriteLine("");
                return(View());
            }

            //{
            //    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 Newresponse = manager.SendAction(config);
            //    Console.WriteLine(Newresponse);
            //}
        }
Example #8
0
 private static void manager_HandleNewExtentEvent(object sender, NewExtenEvent e)
 {
     if (e.Context == "demoagiaction")
     {
         var playTtMonkeyAgiAction = new AgiAction(e.Channel, "EXEC playback tt-monkeys");
         //var answerAgiAction = new AgiAction(e.Channel, "STREAM FILE tt-monkeys"); // can also be used with other commands
         manager.SendAction(playTtMonkeyAgiAction, 30000);
     }
 }
Example #9
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();
        }
Example #10
0
        public static string GetSipChannel(ManagerConnection _ami)
        {
            MonitorAction m = new MonitorAction()
            {
                Channel = "all"
            };
            var res = _ami.SendAction(m);

            Console.WriteLine($"Get Sip Channel : {res.Response} : {res.Message}");
            return("works");
        }
Example #11
0
        private void ButtonCall_Click(object sender, EventArgs e)
        {
            var from    = TextBoxCallFrom.Text.Trim();
            var to      = TextBoxCallTo.Text.Trim();
            var context = CheckBoxInternal.Checked ? "from-internal" : "from-trunk";

            if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                var originateAction = new OriginateAction();
                originateAction.Channel  = "SIP/" + to;
                originateAction.CallerId = to;
                originateAction.Context  = context;
                originateAction.Exten    = from;
                originateAction.Priority = "1";
                originateAction.Timeout  = 30000;
                originateAction.Async    = true;
                var originateResponse = manager.SendAction(originateAction);

                TextBoxOutput.Text += "-----Originating call-----" + Environment.NewLine + "from " + from + " to " + to + Environment.NewLine + Environment.NewLine;
            }
            else
            {
                TextBoxOutput.Text += "Fill 'call from' and 'call to' fields. " + Environment.NewLine;
            }
        }
Example #12
0
        public IActionResult Index(int page = 1)
        {
            int                      pageSize      = 10;
            int                      count         = 0;
            ManagerResponse          response      = manager.SendAction(new GetConfigAction("sip.conf"));
            List <GetConfigResponse> getConfig     = new List <GetConfigResponse>();
            List <string>            getLines      = new List <string>();
            List <string>            getCategories = new List <string>();

            if (response.IsSuccess())
            {
                GetConfigResponse responseConfig = (GetConfigResponse)response;
                getConfig.Add(responseConfig);
                foreach (var conf in responseConfig.Categories.Keys)
                {
                    count += responseConfig.Categories[conf].Count();
                    getCategories.Add(responseConfig.Categories[conf]);
                    foreach (var keyLine in responseConfig.Lines(conf).Keys)
                    {
                        getLines.Add(responseConfig.Lines(conf)[keyLine]);
                    }
                }

                var            items         = getCategories.Skip((page - 1) * pageSize).Take(pageSize).ToList();
                PageViewModel  pageViewModel = new PageViewModel(count, page, pageSize);
                IndexViewModel viewModel     = new IndexViewModel
                {
                    PageViewModel      = pageViewModel,
                    GetConfigResponses = getConfig,
                    Categories         = getCategories,
                    Lines = getLines
                };
                return(View(viewModel));
            }
            else
            {
                Console.WriteLine("");
                return(View());
            }
        }
Example #13
0
        private void ToolStripMenuItem_Click_Event(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripItem item = e.ClickedItem;

            Log("History: ToolStripMenuItem_Click_Event");
            AsteriskPhoneAgentForm asterfm;

            asterfm = this.Owner as AsteriskPhoneAgentForm;
            if (item.Text.Contains("Call"))
            {
                if (RINGENABLED != false)
                {
                    CALLTO = item.Text.Replace("Call - ", string.Empty);

                    OriginateAction oa = new OriginateAction();
                    // Context: Название контекста для совершения исходящего вызова (используется только совместно с параметрами Exten и Priority)
                    oa.Context = ORIGINATE_CONTEXT;     // from-internal

                    // Priority: Priority to use on connect (используется только совместно с параметрами Context и Exten)
                    oa.Priority = ORIGINATE_PRIORITY;     // 1

                    // Exten: Extension to use on connect (используется только совместно с параметрами Context и Priority)
                    oa.Exten = CALLTO;

                    //CallerID: Значение CallerID, используемое для совершения исходящего вызова.
                    oa.CallerId = USER_ID;

                    // Channel: Название канала, с которого совершается исходящий вызов (В том же формате, как если бы Вы совершали вызов этому абоненту командой Dial.)
                    oa.Channel = ASTERISK_PEER_NUMBER;     // SIP/1001

                    // Timeout: Таймаут (в миллисекундах) для соединения с инициатором исходящего вызова (значение по умолчанию: 30000 миллисекунд).
                    oa.Timeout = ORIGINATE_TIMEOUT;

                    // Async: Если указано “true” исходящий вызов будет производиться асинхронно.
                    // Результат ее выполнения будет возвращен позже, в пакете типа “Event”
                    // (позволяет осуществлять несколько вызовов без ожидания результата предыдущей команды, совершающей исходящий вызов)
                    oa.Async = true;

                    ManagerResponse originateResponse = manager.SendAction(oa, oa.Timeout);

                    if (originateResponse.Response.Contains("Success"))
                    {
                        Log("Call to " + CALLTO + " initialized");
                        //Tray.ShowBalloonTip(500, "Call", "Call to " + CALLTO + " initialized", ToolTipIcon.Info);
                    }
                    else
                    {
                        Log("Error: Call to " + CALLTO + " not success");
                    }
                }
            }
        }
Example #14
0
        public async Task <bool> MakeCall(string phone, string voiceUrl, string voiceName, string baseVoiceName)
        {
            var action = new OriginateAction
            {
                Async    = true,
                Channel  = $"Dongle/dongle0/{phone}",
                Exten    = "s",
                Context  = "outgoing",
                Variable = $"SOUND_URL={voiceUrl},SOUND_NAME={voiceName},BASE_SOUND_NAME={baseVoiceName}"
            };

            var response = _managerConnection.SendAction(action);

            return(response.IsSuccess());
        }
Example #15
0
 public async static Task TransferChannel(ManagerConnection ami, string channel, string destination)
 {
     await Task.Run(() =>
     {
         RedirectAction r = new RedirectAction()
         {
             Channel  = channel,
             Exten    = destination,
             Context  = "bbs-pabx",
             Priority = 1
         };
         var res = (ami.SendAction(r));
         res.Dump();
     });
 }
Example #16
0
 public static void CallToPhone(string phone, string name)
 {
     try
     {
         OriginateAction action = new OriginateAction();
         action.Channel  = "SIP/" + Properties.Settings.Default.Phone;
         action.CallerId = "Набор номера: " + name;
         action.Exten    = phone;
         action.Context  = "call-out";
         action.Priority = "0";
         action.Async    = true;
         manager.SendAction(action);
     }
     catch (Exception err)
     {
         LogWriter.Instance.WriteToLog("CallToPhone error " + err.Message);
     }
 }
Example #17
0
 private void RequestQueuesStatus()
 {
     try
     {
         var response = managerConnection.SendAction(new QueueStatusAction());
         if (response.IsSuccess())
         {
             UpdateQueueStatusRequestStateIndicator("TX OK");
         }
         else
         {
             UpdateQueueStatusRequestStateIndicator("RX ER");
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
 public void Originate(string channel, string number)
 {
     try
     {
         _connection.SendAction(new OriginateAction()
         {
             Channel  = String.Format("SIP/{0}", channel),
             Exten    = number,
             Context  = "from-internal",
             Priority = "1",
             CallerId = channel,
             Timeout  = 3000000
         });
         AsteriskEvent(this, new AsteriskEventArgs("calling", "OK"));
     }
     catch (Exception e)
     {
         AsteriskEvent(this, new AsteriskEventArgs("calling", e.StackTrace));
     }
 }
Example #19
0
 public static bool RedirectCall(ManagerConnection ami, string destination, string channel = null)
 {
     try
     {
         RedirectAction r = new RedirectAction()
         {
             Channel  = channel,
             Exten    = destination,
             Context  = "bbs-pabx",
             Priority = 1
         };
         r.Dump();
         var res = (ami.SendAction(r));
         return(res.IsSuccess());
     }
     catch
     {
         MessageBox.Show("Failed to transfer call, sorry for any inconveniences.", "Call Transfer Failed", MessageBoxButton.OK, MessageBoxImage.Error);
         return(false);
     }
 }
Example #20
0
        public static int GetExtensionStatus(ManagerConnection ami, int number)
        {
            ExtensionStateAction a = new ExtensionStateAction()
            {
                Exten    = number.ToString(),
                Context  = "blf",
                ActionId = "1"
            };
            int res = 4;
            ExtensionStateResponse response = null;

            try
            {
                response = (ExtensionStateResponse)ami.SendAction(a);
                res      = response.Status;
            }
            catch // if the response is invalid due to a broken extension, set the value to 0
            {
                Console.WriteLine("Bad cast, " + a.Exten);
            }
            return(res);
        }
Example #21
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();
        }
Example #22
0
        public string Call(string caller, string callee)
        {
            //throw new NotImplementedException();
            log.Debug("Make call from " + caller + " to " + callee);
            OriginateAction newCall = new OriginateAction();

            newCall.CallerId = caller;
            //newCall.Channel = "SIP/1000";
            newCall.Channel = "SIP/" + caller;
            //newCall.Context = "app-dialvm";
            newCall.Context  = Properties.Settings.Default.DefaultContext;
            newCall.Priority = 1;
            //newCall.Exten = "*98";
            newCall.Exten   = callee;
            newCall.Timeout = 30000;
            newCall.Async   = false;
            string result = _manager.SendAction(newCall, 10000).ToString();

            log.Debug("Result: " + result);
            return(result);
        }
Example #23
0
        private void DialNumber(string numberToCall)
        {
            try
            {
                var resp = AstCon.SendAction(new OriginateAction
                {
                    Channel =
                        ConfigurationManager.AppSettings["astPeerType"] + "/" +
                        ConfigurationManager.AppSettings["astPeerID"],
                    Exten    = numberToCall,
                    Context  = ConfigurationManager.AppSettings["astExtenContext"],
                    Priority = "1",
                    CallerId = ConfigurationManager.AppSettings["astExten"],
                    Timeout  = 30000,
                    Async    = true
                });

                LogCall(numberToCall, "Outbound");
            }
            catch
            {
            }
        }
        /// <summary>
        /// Reads line by line from the asterisk server, sets the protocol identifier as soon as it is
        /// received and dispatches the received events and responses via the associated dispatcher.
        /// </summary>
        /// <seealso cref="ManagerConnection.DispatchEvent(ManagerEvent)" />
        /// <seealso cref="ManagerConnection.DispatchResponse(Response.ManagerResponse)" />
        /// <seealso cref="ManagerConnection.setProtocolIdentifier(String)" />
        internal void Run()
        {
            if (mrSocket == null)
            {
                throw new SystemException("Unable to run: socket is null.");
            }

            string line;

            while (true)
            {
                try
                {
                    while (!die)
                    {
                        #region check line from *

                        if (!is_logoff)
                        {
                            if (mrSocket != null && mrSocket.Initial)
                            {
                                Reinitialize();
                            }
                            else if (disconnect)
                            {
                                disconnect = false;
                                mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
                            }
                        }
                        if (lineQueue.Count == 0)
                        {
                            if (lastPacketTime.AddMilliseconds(mrConnector.PingInterval) < DateTime.Now &&
                                mrConnector.PingInterval > 0 &&
                                mrSocket != null &&
                                !wait4identiier &&
                                !is_logoff
                                )
                            {
                                if (pingHandler != null)
                                {
                                    if (pingHandler.Response == null)
                                    {
                                        // If one PingInterval from Ping without Pong then send Disconnect event
                                        mrConnector.RemoveResponseHandler(pingHandler);
                                        mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
                                    }
                                    pingHandler.Free();
                                    pingHandler = null;
                                }
                                else
                                {
                                    // Send PING to *
                                    try
                                    {
                                        pingHandler = new ResponseHandler(new PingAction(), null);
                                        mrConnector.SendAction(pingHandler.Action, pingHandler);
                                    }
                                    catch
                                    {
                                        disconnect = true;
                                        mrSocket   = null;
                                    }
                                }
                                lastPacketTime = DateTime.Now;
                            }
                            Thread.Sleep(50);

                            continue;
                        }

                        #endregion

                        lastPacketTime = DateTime.Now;
                        lock (((ICollection)lineQueue).SyncRoot)
                            line = lineQueue.Dequeue().Trim();
#if LOGGER
                        logger.Debug(line);
#endif

                        #region processing Response: Follows

                        if (processingCommandResult)
                        {
                            string lineLower = line.ToLower(Helper.CultureInfo);
                            if (lineLower == "--end command--")
                            {
                                var commandResponse = new CommandResponse();
                                Helper.SetAttributes(commandResponse, packet);
                                commandList.Add(line);
                                commandResponse.Result  = commandList;
                                processingCommandResult = false;
                                packet.Clear();
                                mrConnector.DispatchResponse(commandResponse);
                            }
                            else if (lineLower.StartsWith("privilege: ") ||
                                     lineLower.StartsWith("actionid: ") ||
                                     lineLower.StartsWith("timestamp: ") ||
                                     lineLower.StartsWith("server: ")
                                     )
                            {
                                Helper.AddKeyValue(packet, line);
                            }
                            else
                            {
                                commandList.Add(line);
                            }
                            continue;
                        }

                        #endregion

                        #region collect key: value and ProtocolIdentifier

                        if (!string.IsNullOrEmpty(line))
                        {
                            if (wait4identiier && line.StartsWith("Asterisk Call Manager"))
                            {
                                wait4identiier = false;
                                var connectEvent = new ConnectEvent(mrConnector);
                                connectEvent.ProtocolIdentifier = line;
                                mrConnector.DispatchEvent(connectEvent);
                                continue;
                            }
                            if (line.Trim().ToLower(Helper.CultureInfo) == "response: follows")
                            {
                                // Switch to wait "--END COMMAND--" mode
                                processingCommandResult = true;
                                packet.Clear();
                                commandList.Clear();
                                Helper.AddKeyValue(packet, line);
                                continue;
                            }
                            Helper.AddKeyValue(packet, line);
                            continue;
                        }

                        #endregion

                        #region process events and responses

                        if (packet.ContainsKey("event"))
                        {
                            mrConnector.DispatchEvent(packet);
                        }

                        else if (packet.ContainsKey("response"))
                        {
                            mrConnector.DispatchResponse(packet);
                        }

                        #endregion

                        packet.Clear();
                    }
                    if (mrSocket != null)
                    {
                        mrSocket.Close();
                    }
                    break;
                }
#if LOGGER
                catch (Exception ex)
                {
                    logger.Info("Exception : {0}", ex.Message);
#else
                catch
                {
#endif
                }

                if (die)
                {
                    break;
                }

#if LOGGER
                logger.Info("No die, any error - send disconnect.");
#endif
                mrConnector.DispatchEvent(new DisconnectEvent(mrConnector));
            }
        }
Example #25
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();
        }
Example #26
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);
        }
Example #27
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);
        }
Example #28
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);
        }
Example #29
0
        void manager_UnhandledEvent(object sender, ManagerEvent e)
        {
            log.Debug("New unhandled event received: " + e.GetType().Name);
            LineControl lc = null;

            //StateServer
            switch (e.GetType().Name)
            {
            case "AGIExecEvent":
                AGIExecEvent agievent = e as AGIExecEvent;
                break;

            case "AlarmClearEvent":
                AlarmClearEvent alarmclear = e as AlarmClearEvent;
                break;

            case "AlarmEvent":
                AlarmEvent alarmevent = e as AlarmEvent;
                break;

            case "AsyncAGIEvent":
                AsyncAGIEvent asyncagievent = e as AsyncAGIEvent;
                break;

            case "BridgeEvent":
                BridgeEvent bridgeevent = e as BridgeEvent;
                break;

            case "CdrEvent":
                CdrEvent cdrevent = e as CdrEvent;
                break;

            case "ChannelReloadEvent":
                ChannelReloadEvent channelreload = e as ChannelReloadEvent;
                break;

            case "ChannelUpdateEvent":
                ChannelUpdateEvent channelupdate = e as ChannelUpdateEvent;
                break;

            case "ConnectEvent":
                ConnectEvent connectevent = e as ConnectEvent;
                break;

            case "ConnectionStateEvent":
                ConnectionStateEvent connectionstate = e as ConnectionStateEvent;
                break;

            case "DBGetResponseEvent":
                DBGetResponseEvent dbget = e as DBGetResponseEvent;
                log.Debug("DBGet response: " + dbget.ToString());
                switch (dbget.Family)
                {
                case "DND":
                    ss.SetLineControl(setLineControlDND(dbget.Key, true));
                    break;

                case "CF":
                    ss.SetLineControl(setLineControlForward(dbget.Key, dbget.Val));
                    break;
                }
                break;

            case "DialEvent":
                DialEvent dial = e as DialEvent;
                log.Debug("Dial event: " + dial.ToString());
                break;

            case "DisconnectEvent":
                DisconnectEvent disconnect = e as DisconnectEvent;
                log.Debug("Disconnect event: " + disconnect.ToString());
                break;

            case "DNDStateEvent":
                DNDStateEvent dndstate = e as DNDStateEvent;
                log.Debug("DND state event: " + dndstate.ToString());
                break;

            case "ExtensionStatusEvent":
                ExtensionStatusEvent extensionstatus = e as ExtensionStatusEvent;
                log.Debug("Extension status event: " + extensionstatus.ToString() + ", status: " + extensionstatus.Status + ", hint: " + extensionstatus.Hint);
                ss.SetLineControl(getLineControlFromExtensionStatusEvent(extensionstatus));
                break;

            case "FaxReceivedEvent":
                FaxReceivedEvent faxreceived = e as FaxReceivedEvent;
                break;

            case "HangupEvent":
                HangupEvent hangup = e as HangupEvent;
                log.Debug("Hangup event: " + hangup.ToString() + " callerid: " + hangup.CallerId + " calleridnum: " + hangup.CallerIdNum);
                //line control
                if (channels.Contains(hangup.Channel))
                {
                    lc = getLineControl((string)channels[hangup.Channel]);
                    int hi = 0;
                    LineControlConnection[] newLCC = null;
                    if (lc.lineControlConnection.Length > 1)
                    {
                        newLCC = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection hlcc in lc.lineControlConnection)
                        {
                            if (hlcc.callid != hangup.Channel)
                            {
                                newLCC[hi] = hlcc;
                                hi++;
                            }
                        }
                    }
                    lc.lineControlConnection = newLCC;
                    ss.SetLineControl(lc);
                    channels.Remove(hangup.Channel);
                }

                //missed calls
                callToFind = hangup.UniqueId.Substring(0, 6) + "," + hangup.UniqueId.Substring(6);
                Call mCall = missedCalls.Find(FindCall);
                if (mCall != null)
                {
                    log.Debug("Missed call finded for callid: " + hangup.UniqueId);
                    AddCallLogs(mCall.callee, mCall);
                    if (missedCalls.Remove(mCall))
                    {
                        log.Debug("Call " + mCall.callId + " successfully removed from missedcall cache");
                    }
                    else
                    {
                        log.Debug("Call " + mCall.callId + " cannot be removed from missedcall cache");
                    }
                }
                break;

            case "HoldedCallEvent":
                HoldedCallEvent holdedcall = e as HoldedCallEvent;
                break;

            case "HoldEvent":
                HoldEvent holdevent = e as HoldEvent;
                break;

            case "JabberEvent":
                JabberEvent jabberevent = e as JabberEvent;
                break;

            case "JitterBufStatsEvent":
                JitterBufStatsEvent jitter = e as JitterBufStatsEvent;
                break;

            case "JoinEvent":
                JoinEvent join = e as JoinEvent;
                break;

            case "LeaveEvent":
                LeaveEvent leave = e as LeaveEvent;
                break;

            case "LinkEvent":
                LinkEvent link = e as LinkEvent;
                log.Debug("Link event: " + link.ToString());
                lc = getLineControl(link.CallerId1);
                if (lc != null)
                {
                    foreach (LineControlConnection linklcc in lc.lineControlConnection)
                    {
                        if (linklcc.callid == link.Channel1)
                        {
                            linklcc.contact = link.CallerId2;
                            ss.SetLineControl(lc);
                            break;
                        }
                    }
                }
                lc = getLineControl(link.CallerId2);
                if (lc != null)
                {
                    foreach (LineControlConnection linklcc in lc.lineControlConnection)
                    {
                        if (linklcc.callid == link.Channel2)
                        {
                            linklcc.contact = link.CallerId1;
                            ss.SetLineControl(lc);
                            break;
                        }
                    }
                }
                break;

            case "LogChannelEvent":
                LogChannelEvent logchannel = e as LogChannelEvent;
                break;

            case "ManagerEvent":
                ManagerEvent managerevent = e;
                break;

            case "MeetmeEndEvent":
                MeetmeEndEvent meetmeend = e as MeetmeEndEvent;
                break;

            case "MeetmeJoinEvent":
                MeetmeJoinEvent meetmejoin = e as MeetmeJoinEvent;
                break;

            case "MeetmeLeaveEvent":
                MeetmeLeaveEvent meetmeleave = e as MeetmeLeaveEvent;
                break;

            case "MeetmeMuteEvent":
                MeetmeMuteEvent meetmemute = e as MeetmeMuteEvent;
                break;

            case "MeetmeStopTalkingEvent":
                MeetmeStopTalkingEvent meetmestoptalking = e as MeetmeStopTalkingEvent;
                break;

            case "MeetmeTalkingEvent":
                MeetmeTalkingEvent meetmetalking = e as MeetmeTalkingEvent;
                break;

            case "MeetmeTalkRequestEvent":
                MeetmeTalkRequestEvent meetmetalkrequest = e as MeetmeTalkRequestEvent;
                break;

            case "MessageWaitingEvent":
                MessageWaitingEvent messagewaiting = e as MessageWaitingEvent;
                log.Debug("Message waiting event: " + messagewaiting.ToString());
                lc = getLineControl(messagewaiting.Mailbox.Substring(0, messagewaiting.Mailbox.IndexOf("@")));
                if (lc != null)
                {
                    if (messagewaiting.Waiting > 0)
                    {
                        lc.mwiOn = true;
                    }
                    else
                    {
                        lc.mwiOn = false;
                    }
                    ss.SetLineControl(lc);
                }
                break;

            case "MobileStatusEvent":
                MobileStatusEvent mobilestatus = e as MobileStatusEvent;
                break;

            case "ModuleLoadReportEvent":
                ModuleLoadReportEvent moduleload = e as ModuleLoadReportEvent;
                break;

            case "MonitorStartEvent":
                MonitorStartEvent monitorstart = e as MonitorStartEvent;
                break;

            case "MonitorStopEvent":
                MonitorStopEvent monitorstop = e as MonitorStopEvent;
                break;

            case "NewAccountCodeEvent":
                NewAccountCodeEvent newaccountcode = e as NewAccountCodeEvent;
                break;

            case "NewCallerIdEvent":
                NewCallerIdEvent newcallerid = e as NewCallerIdEvent;
                log.Debug("New caller id envent: " + newcallerid.ToString());
                break;

            case "NewChannelEvent":
                NewChannelEvent newchannel = e as NewChannelEvent;
                log.Debug("New Channel event: " + newchannel.ToString());
                CommandAction   ca = new CommandAction("core show channel " + newchannel.Channel);
                CommandResponse cr = (CommandResponse)manager.SendAction(ca, 10000);
                log.Debug("Channel info: " + cr.ToString());
                string dn = newchannel.CallerIdNum;
                log.Debug("Retreive call information...");
                bool callerIdUnknown = true;
                if (newchannel.CallerIdNum != "<unknown>")
                {
                    callerIdUnknown = false;
                }
                else
                {
                    foreach (string s in cr.Result)
                    {
                        if (s.Contains("Caller ID:"))
                        {
                            dn = s.Substring(s.LastIndexOf(" "));
                            break;
                        }
                    }
                }
                Call newOutboundCall = getOutboundCallFromChannelInfo(cr.Result, callerIdUnknown);
                if (newOutboundCall != null)
                {
                    Call missedCall = newOutboundCall;
                    AddCallLogs(dn, newOutboundCall);
                    dnToFind = newOutboundCall.callee;
                    if (linecontrols.Find(FindLineControl) != null)
                    {
                        log.Debug("This call will be put in missedcall cache: " + missedCall.callId);
                        missedCall.type = CallType.missed;
                        missedCalls.Add(missedCall);
                    }
                }
                break;

            case "NewExtenEvent":
                NewExtenEvent newexten = e as NewExtenEvent;
                log.Debug("New exten event: " + newexten.ToString());
                string   channel      = "";
                char[]   splitter     = { '/' };
                string[] splitchannel = newexten.Channel.Split(splitter);
                splitter[0]  = '-';
                splitchannel = splitchannel[1].Split(splitter);
                channel      = splitchannel[0];
                //DND?
                if (newexten.Extension == Properties.Settings.Default.FeatureCodeDNDToggle && newexten.Application == "Playback")
                {
                    switch (newexten.AppData)
                    {
                    case "do-not-disturb&activated":
                        log.Debug("Successfully activate dnd for channel: " + channel);
                        ss.SetLineControl(setLineControlDND(channel, true));
                        break;

                    case "do-not-disturb&de-activated":
                        log.Debug("Successfully deactivate dnd for channel: " + channel);
                        ss.SetLineControl(setLineControlDND(channel, false));
                        break;
                    }
                }
                //Forward all?
                else if (newexten.Extension.Contains(Properties.Settings.Default.FeatureCodeCallForwardAllActivate) && newexten.Application == "Playback" && newexten.AppData == "call-fwd-unconditional&for&extension")
                {
                    string forward = newexten.Extension.Substring(Properties.Settings.Default.FeatureCodeCallForwardAllActivate.Length);
                    log.Debug("Call forward all from channel: " + channel + " to " + forward);
                    ss.SetLineControl(setLineControlForward(channel, forward));
                }
                // UnForwardAll
                else if (newexten.Extension == Properties.Settings.Default.FeatureCodeCallForwardAllDeactivate && newexten.Application == "Playback" && newexten.AppData == "call-fwd-unconditional&de-activated")
                {
                    log.Debug("Call unforward all from channel: " + channel);
                    ss.SetLineControl(setLineControlForward(channel, ""));
                }
                break;

            case "NewStateEvent":
                NewStateEvent newstate = e as NewStateEvent;
                log.Debug("New State event: " + newstate.ToString());
                LineControl             newstateLc   = getLineControl(newstate.CallerId);
                LineControlConnection[] newStateLccs = null;
                int i = 0;
                if (newstateLc.lineControlConnection != null)
                {
                    bool isContained = false;
                    foreach (LineControlConnection elcc in newstateLc.lineControlConnection)
                    {
                        if (elcc.callid == newstate.Channel)
                        {
                            isContained  = true;
                            newStateLccs = newstateLc.lineControlConnection;
                            break;
                        }
                        i++;
                    }
                    if (!isContained)
                    {
                        i            = 0;
                        newStateLccs = new LineControlConnection[newstateLc.lineControlConnection.Length + 1];
                        foreach (LineControlConnection newstateLcc in newstateLc.lineControlConnection)
                        {
                            newStateLccs[i] = newstateLcc;
                            i++;
                        }
                    }
                }
                else
                {
                    newStateLccs    = new LineControlConnection[1];
                    newStateLccs[0] = new LineControlConnection();
                }
                try
                {
                    switch (newstate.State)
                    {
                    case "Up":
                        //received call?
                        callToFind = newstate.UniqueId;
                        Call rCall = missedCalls.Find(FindCall);
                        if (rCall != null)
                        {
                            log.Debug("Missed call finded: " + callToFind + ", this call will be received");
                            rCall.type = CallType.received;
                            AddCallLogs(rCall.callee, rCall);
                            missedCalls.Remove(rCall);
                        }
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].terminalState = TerminalState.talking;
                        }
                        break;

                    case "Ringing":
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.alerting;
                            newStateLccs[i].terminalState = TerminalState.ringing;
                        }
                        break;

                    case "Ring":
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.alerting;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.dialing;
                            newStateLccs[i].terminalState = TerminalState.inuse;
                        }
                        break;
                    }
                }
                catch (Exception stateException)
                {
                    log.Debug("NewState exception: " + stateException.Message);
                }
                if (newstateLc != null)
                {
                    newstateLc.lineControlConnection = newStateLccs;
                    ss.SetLineControl(newstateLc);
                }
                break;

            case "OriginateResponseEvent":
                OriginateResponseEvent originateresponse = e as OriginateResponseEvent;
                break;

            case "ParkedCallEvent":
                ParkedCallEvent parkedcall = e as ParkedCallEvent;
                break;

            case "ParkedCallGiveUpEvent":
                ParkedCallGiveUpEvent parkedcallgiveup = e as ParkedCallGiveUpEvent;
                break;

            case "ParkedCallsCompleteEvent":
                ParkedCallsCompleteEvent parkedcallscomplete = e as ParkedCallsCompleteEvent;
                break;

            case "ParkedCallTimeOutEvent":
                ParkedCallTimeOutEvent parkedcalltimeout = e as ParkedCallTimeOutEvent;
                break;

            case "PeerEntryEvent":
                log.Debug("SipAction: one peer entry event received, " + e.ToString());
                PeerEntryEvent peerentry = e as PeerEntryEvent;
                peers.Add(peerentry);
                ss.SetLineControl(getLineControlFromPeerEntry(peerentry));
                break;

            case "PeerlistCompleteEvent":
                log.Debug("SipAction: peer list completed " + e.ToString());
                PeerlistCompleteEvent peerlistcomplete = e as PeerlistCompleteEvent;
                acs.setPeers(peers);
                break;

            case "PeerStatusEvent":
                PeerStatusEvent peerstatus = e as PeerStatusEvent;
                log.Debug("Peer status: " + peerstatus.ToString());
                break;

            case "PRIEvent":
                PRIEvent pri = e as PRIEvent;
                break;

            case "RegistryEvent":
                RegistryEvent registry = e as RegistryEvent;
                break;

            case "ReloadEvent":
                ReloadEvent reload = e as ReloadEvent;
                break;

            case "RenameEvent":
                RenameEvent rename = e as RenameEvent;
                break;

            case "ResponseEvent":
                ResponseEvent response = e as ResponseEvent;
                break;

            case "RTCPReceivedEvent":
                RTCPReceivedEvent rtcpreceived = e as RTCPReceivedEvent;
                break;

            case "RTCPSentEvent":
                RTCPSentEvent rtcpsent = e as RTCPSentEvent;
                break;

            case "RTPReceiverStatEvent":
                RTPReceiverStatEvent rtpreceiver = e as RTPReceiverStatEvent;
                break;

            case "RTPSenderStatEvent":
                RTPSenderStatEvent rtpsender = e as RTPSenderStatEvent;
                break;

            case "ShowDialPlanCompleteEvent":
                ShowDialPlanCompleteEvent showdialplan = e as ShowDialPlanCompleteEvent;
                break;

            case "ShutdownEvent":
                ShutdownEvent shutdown = e as ShutdownEvent;
                break;

            case "StatusCompleteEvent":
                StatusCompleteEvent statuscomplete = e as StatusCompleteEvent;
                break;

            case "StatusEvent":
                StatusEvent status = e as StatusEvent;
                break;

            case "TransferEvent":
                TransferEvent transfer = e as TransferEvent;
                break;

            case "UnholdEvent":
                UnholdEvent unhold = e as UnholdEvent;
                break;

            case "UnknownEvent":
                UnknownEvent unknown = e as UnknownEvent;
                break;

            case "UnlinkEvent":
                UnlinkEvent unlink = e as UnlinkEvent;
                log.Debug("Unlink event : " + unlink.ToString());
                LineControlConnection[] lccs = null;
                i  = 0;
                lc = getLineControl(unlink.CallerId1);
                if (lc != null)
                {
                    if (lc.lineControlConnection.Length > 1)
                    {
                        lccs = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection linklcc in lc.lineControlConnection)
                        {
                            if (linklcc.callid != unlink.Channel1)
                            {
                                lccs[i] = linklcc;
                                i++;
                                break;
                            }
                        }
                    }
                    else
                    {
                        lc.lineControlConnection = null;
                    }
                    ss.SetLineControl(lc);
                }
                i  = 0;
                lc = getLineControl(unlink.CallerId2);
                if (lc != null)
                {
                    if (lc.lineControlConnection.Length > 1)
                    {
                        lccs = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection linklcc in lc.lineControlConnection)
                        {
                            if (linklcc.callid != unlink.Channel2)
                            {
                                lccs[i] = linklcc;
                                i++;
                                break;
                            }
                        }
                    }
                    else
                    {
                        lc.lineControlConnection = null;
                    }
                    ss.SetLineControl(lc);
                }
                break;

            case "UnparkedCallEvent":
                UnparkedCallEvent unparked = e as UnparkedCallEvent;
                break;

            case "UserEvent":
                UserEvent user = e as UserEvent;
                break;

            case "VarSetEvent":
                VarSetEvent varset = e as VarSetEvent;
                break;

            case "ZapShowChannelsCompleteEvent":
                ZapShowChannelsCompleteEvent zapshowchannelscomplete = e as ZapShowChannelsCompleteEvent;
                break;

            case "ZapShowChannelsEvent":
                ZapShowChannelsEvent zapshowchannels = e as ZapShowChannelsEvent;
                break;
            }
            //ACDConnector
            switch (e.GetType().Name)
            {
            case "AgentCallbackLoginEvent":
                AgentCallbackLoginEvent agentcallbacklogin = e as AgentCallbackLoginEvent;
                break;

            case "AgentCallbackLogoffEvent":
                AgentCallbackLogoffEvent agentcallbacklogoff = e as AgentCallbackLogoffEvent;
                break;

            case "AgentCalledEvent":
                AgentCalledEvent agentcalled = e as AgentCalledEvent;
                break;

            case "AgentCompleteEvent":
                AgentCompleteEvent agentcomplete = e as AgentCompleteEvent;
                break;

            case "AgentConnectEvent":
                AgentConnectEvent agentconnect = e as AgentConnectEvent;
                break;

            case "AgentDumpEvent":
                AgentDumpEvent agentdump = e as AgentDumpEvent;
                break;

            case "AgentLoginEvent":
                AgentLoginEvent agentlogin = e as AgentLoginEvent;
                break;

            case "AgentLogoffEvent":
                AgentLogoffEvent agentlogoff = e as AgentLogoffEvent;
                break;

            case "AgentsCompleteEvent":
                AgentsCompleteEvent agentscomplete = e as AgentsCompleteEvent;
                break;

            case "AgentsEvent":
                AgentsEvent agentevent = e as AgentsEvent;
                break;

            case "QueueCallerAbandonEvent":
                QueueCallerAbandonEvent queuecallerabandon = e as QueueCallerAbandonEvent;
                break;

            case "QueueEntryEvent":
                QueueEntryEvent queueentry = e as QueueEntryEvent;
                break;

            case "QueueEvent":
                QueueEvent queue = e as QueueEvent;
                break;

            case "QueueMemberEvent":
                QueueMemberEvent queuemember = e as QueueMemberEvent;
                break;

            case "QueueMemberPausedEvent":
                QueueMemberPausedEvent queuememberpaused = e as QueueMemberPausedEvent;
                break;

            case "QueueMemberPenaltyEvent":
                QueueMemberPenaltyEvent queuememberpenalty = e as QueueMemberPenaltyEvent;
                break;

            case "QueueMemberRemovedEvent":
                QueueMemberRemovedEvent queuememberremoved = e as QueueMemberRemovedEvent;
                break;

            case "QueueMemberStatusEvent":
                QueueMemberStatusEvent queuememberstatus = e as QueueMemberStatusEvent;
                break;

            case "QueueParamsEvent":
                QueueParamsEvent queueparams = e as QueueParamsEvent;
                break;

            case "QueueStatusCompleteEvent":
                QueueStatusCompleteEvent queuestatuscomplete = e as QueueStatusCompleteEvent;
                break;
            }
        }
Example #30
0
        private void button1_Click(object sender, EventArgs e)
        {
            ///****************    office asterisk
            // *
            //channel originate sip/ast2/70019779805550000 extension 100@autodialer

            long initBNumber = 70019779805550000;

            //long initBNumber = 80019779805550000;

            long initANumber = 97477009999;


            for (int i = 0; i < 100; i++)
            {
                OriginateAction oc = new OriginateAction();
                oc.Async    = true;
                oc.Context  = @"autodialer";
                oc.Priority = "1";
                //oc.Channel = @"sip/ast2/70019779805550000";

                oc.Channel = @"sip/ast2/" + (initBNumber + i).ToString();


                //oc.CallerId = "97477009999";

                oc.CallerId = (initANumber + i).ToString();
                oc.Exten    = "100";
                oc.Timeout  = ORIGINATE_TIMEOUT;
                manager.SendAction(oc, null);
            }



            //********/



            // my banwagon

            //OriginateAction oc1 = new OriginateAction();
            //oc1.Context = @"from-internel";
            //oc1.Priority = "1";
            //oc1.Channel = @"pjsip/7001";
            //oc1.CallerId = "97477009999";
            //oc1.Exten = "100";
            //oc1.Async = true;
            //oc1.Timeout = ORIGINATE_TIMEOUT;

            //manager.SendAction(oc1, null);



            //


            //OriginateAction oc1 = new OriginateAction();
            //oc1.Context = @"autodialer";
            //oc1.Priority = "1";
            //oc1.Channel = @"sip/ast2/70019779805550000";
            //oc1.CallerId = "97477009999";
            //oc1.Exten = "100";
            //oc1.Timeout = ORIGINATE_TIMEOUT;
            //manager.SendAction(oc1, null);


            //

            //OriginateAction oc2 = new OriginateAction();
            //oc2.Context = @"autodialer";
            //oc2.Priority = "1";
            //oc2.Channel = @"sip/ast2/70019779805550000";
            //oc2.CallerId = "97477009999";
            //oc2.Exten = "100";
            //oc2.Timeout = ORIGINATE_TIMEOUT;
            //manager.SendAction(oc2, null);
        }