Example #1
0
        static async Task DialNumber()
        {
            string fromHeader = (new SIPFromHeader(USERNAME, new SIPURI(USERNAME, DOMAIN, null), null)).ToString();

            SIPCallDescriptor callDescriptor = new SIPCallDescriptor(USERNAME, PASSWORD, DEFAULT_CALL_DESTINATION, fromHeader, null, null, null, null, SIPCallDirection.Out, SDP.SDP_MIME_CONTENTTYPE, null, null);

            callDescriptor.CallId = "12028883999";

            userAgent = new SIPUserAgent(sipTransport, null);
            userAgent.ClientCallTrying   += (uac, resp) => Console.WriteLine($"{uac.CallDescriptor.To} Trying: {resp.StatusCode} {resp.ReasonPhrase}.");
            userAgent.ClientCallRinging  += (uac, resp) => Console.WriteLine($"{uac.CallDescriptor.To} Ringing: {resp.StatusCode} {resp.ReasonPhrase}.");
            userAgent.ClientCallFailed   += (uac, err, resp) => Console.WriteLine($"{uac.CallDescriptor.To} Failed: {err}, Status code: {resp?.StatusCode}");
            userAgent.ClientCallAnswered += (uac, resp) => Console.WriteLine($"{uac.CallDescriptor.To} Answered: {resp.StatusCode} {resp.ReasonPhrase}.");
            userAgent.OnDtmfTone         += (key, duration) => OnDtmfTone(userAgent, key, duration);
            userAgent.OnRtpEvent         += (evt, hdr) => Console.WriteLine($"rtp event {evt.EventID}, duration {evt.Duration}, end of event {evt.EndOfEvent}, timestamp {hdr.Timestamp}, marker {hdr.MarkerBit}.");
            userAgent.OnCallHungup       += OnHangup;

            var rtpSession = new RtpAVSession(
                new AudioOptions
            {
                AudioSource = AudioSourcesEnum.CaptureDevice,
                AudioCodecs = new List <SDPMediaFormatsEnum> {
                    SDPMediaFormatsEnum.PCMU, SDPMediaFormatsEnum.PCMA
                }
            },
                null);

            rtpSession.OnRtpPacketReceived += OnRtpPacketReceived;

            var callResult = await userAgent.Call(callDescriptor, rtpSession);

            Console.WriteLine($"Call result {((callResult) ? "success" : "failure")}.");
            if (callResult)
            {
                Console.WriteLine("Enter digits one after another");
                for (int i = 0; i < 11; i++)
                {
                    var p = Console.ReadLine();
                    await userAgent.SendDtmf(byte.Parse(p));
                }
            }
            Console.WriteLine("Enter ?");
            Console.ReadLine();
            await userAgent.SendDtmf(35);

            Thread.Sleep(60000);

            userAgent.Hangup();
            _waveFile.Dispose();
            Console.WriteLine("Hangup");
        }
Example #2
0
 /// <summary>
 /// Requests the RTP session to send a RTP event representing a DTMF tone to the
 /// remote party.
 /// </summary>
 /// <param name="tone">A byte representing the tone to send. Must be between 0 and 15.</param>
 public Task SendDTMF(byte tone)
 {
     if (m_userAgent != null)
     {
         return(m_userAgent.SendDtmf(tone));
     }
     else
     {
         return(Task.FromResult(0));
     }
 }
Example #3
0
        static async Task Main()
        {
            Console.WriteLine("SIPSorcery Send DTMF Tones example.");
            Console.WriteLine("Press ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource rtpCts = new CancellationTokenSource(); // Cancellation token to stop the RTP stream.

            AddConsoleLogger();

            var sipTransport = new SIPTransport();
            var userAgent    = new SIPUserAgent(sipTransport, null);
            var rtpSession   = new RtpAVSession(new AudioOptions {
                AudioSource = AudioSourcesEnum.CaptureDevice
            }, null);

            // Place the call and wait for the result.
            bool callResult = await userAgent.Call(DEFAULT_DESTINATION_SIP_URI, null, null, rtpSession);

            // Ctrl-c will gracefully exit the call at any point.
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                rtpCts.Cancel();
            };

            if (callResult)
            {
                Console.WriteLine("Call attempt successful.");

                // Give the call some time to answer.
                await Task.Delay(1000);

                // Send the DTMF tones.
                await userAgent.SendDtmf(0x05);

                await Task.Delay(2000);

                await userAgent.SendDtmf(0x09);

                await Task.Delay(2000);

                await userAgent.SendDtmf(0x02);

                await Task.Delay(2000);

                if (userAgent.IsCallActive)
                {
                    Console.WriteLine("Hanging up.");
                    rtpCts.Cancel();
                    userAgent.Hangup();
                }
            }
            else
            {
                Console.WriteLine("Call attempt failed.");
            }

            Log.LogInformation("Exiting...");

            // Clean up.
            sipTransport.Shutdown();
            SIPSorcery.Net.DNSManager.Stop();
        }
Example #4
0
        /// <summary>
        /// Because this is a server user agent the SIP transport must start listening for client user agents.
        /// </summary>
        private static async Task OnRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest)
        {
            try
            {
                if (sipRequest.Header.From != null &&
                    sipRequest.Header.From.FromTag != null &&
                    sipRequest.Header.To != null &&
                    sipRequest.Header.To.ToTag != null)
                {
                    // This is an in-dialog request that will be handled directly by a user agent instance.
                }
                else if (sipRequest.Method == SIPMethodsEnum.INVITE)
                {
                    Log.LogInformation($"Incoming call request: {localSIPEndPoint}<-{remoteEndPoint} {sipRequest.URI}.");

                    SIPUserAgent ua = new SIPUserAgent(_sipTransport, null);
                    ua.OnCallHungup              += OnHangup;
                    ua.ServerCallCancelled       += (uas) => Log.LogDebug("Incoming call cancelled by remote party.");
                    ua.OnDtmfTone                += (key, duration) => OnDtmfTone(ua, key, duration);
                    ua.OnRtpEvent                += (evt, hdr) => Log.LogDebug($"rtp event {evt.EventID}, duration {evt.Duration}, end of event {evt.EndOfEvent}, timestamp {hdr.Timestamp}, marker {hdr.MarkerBit}.");
                    ua.OnTransactionTraceMessage += (tx, msg) => Log.LogDebug($"uas tx {tx.TransactionId}: {msg}");
                    ua.ServerCallRingTimeout     += (uas) =>
                    {
                        Log.LogWarning($"Incoming call timed out in {uas.ClientTransaction.TransactionState} state waiting for client ACK, terminating.");
                        ua.Hangup();
                    };

                    var uas        = ua.AcceptCall(sipRequest);
                    var rtpSession = CreateRtpSession(ua);

                    // Insert a brief delay to allow testing of the "Ringing" progress response.
                    // Without the delay the call gets answered before it can be sent.
                    await Task.Delay(500);

                    await ua.Answer(uas, rtpSession);

                    if (ua.IsCallActive)
                    {
                        _calls.TryAdd(ua.Dialogue.CallId, ua);

                        if (sipRequest.URI.User != null)
                        {
                            if (Int32.TryParse(sipRequest.URI.User, out int dtmfCode))
                            {
                                Log.LogDebug($"URI dtmf code {dtmfCode}.");

                                while (dtmfCode > 0)
                                {
                                    byte dtmfByte = (byte)(dtmfCode % 10);

                                    Log.LogDebug($"Sending DTMF {dtmfByte} to caller.");

                                    if (!ua.IsCallActive)
                                    {
                                        Log.LogWarning($"Client call no longer active.");
                                        break;
                                    }
                                    else
                                    {
                                        await ua.SendDtmf(dtmfByte);
                                    }

                                    dtmfCode /= 10;
                                }
                            }
                        }
                    }
                }
                else if (sipRequest.Method == SIPMethodsEnum.BYE)
                {
                    SIPResponse byeResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.CallLegTransactionDoesNotExist, null);
                    await _sipTransport.SendResponseAsync(byeResponse);
                }
                else if (sipRequest.Method == SIPMethodsEnum.SUBSCRIBE)
                {
                    SIPResponse notAllowededResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
                    await _sipTransport.SendResponseAsync(notAllowededResponse);
                }
                else if (sipRequest.Method == SIPMethodsEnum.OPTIONS || sipRequest.Method == SIPMethodsEnum.REGISTER)
                {
                    SIPResponse optionsResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Ok, null);
                    await _sipTransport.SendResponseAsync(optionsResponse);
                }
            }
            catch (Exception reqExcp)
            {
                Log.LogWarning($"Exception handling {sipRequest.Method}. {reqExcp.Message}");
            }
        }
Example #5
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Blind Transfer Demo: Transferee");
            Console.WriteLine("Waiting for incoming call from Transferor.");
            Console.WriteLine("Press 'q' or ctrl-c to exit.");

            // Plumbing code to facilitate a graceful exit.
            CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.

            AddConsoleLogger();

            // Set up a default SIP transport.
            _sipTransport = new SIPTransport();
            _sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));

            EnableTraceLogs(_sipTransport);

            var userAgent = new SIPUserAgent(_sipTransport, null);

            userAgent.ServerCallCancelled += (uas) => Log.LogDebug("Incoming call cancelled by remote party.");
            userAgent.OnCallHungup        += (dialog) => Log.LogDebug("Call hungup by remote party.");
            userAgent.OnIncomingCall      += async(ua, req) =>
            {
                var rtpAudioSession = new AudioSendOnlyMediaSession();

                var  uas          = ua.AcceptCall(req);
                bool answerResult = await ua.Answer(uas, rtpAudioSession);

                Log.LogDebug($"Answer incoming call result {answerResult}.");

                _ = Task.Run(async() =>
                {
                    await Task.Delay(1000);

                    Log.LogDebug($"Sending DTMF sequence {string.Join("", DTMF_SEQUENCEFOR_TRANSFEROR.Select(x => x))}.");
                    foreach (byte dtmf in DTMF_SEQUENCEFOR_TRANSFEROR)
                    {
                        Log.LogDebug($"Sending DTMF tone to transferor {dtmf}.");
                        await ua.SendDtmf(dtmf);
                    }
                });
            };
            userAgent.OnTransferRequested          += (referredTo, referredBy) => true;
            userAgent.OnTransferToTargetSuccessful += (dst) =>
            {
                Task.Run(async() =>
                {
                    await Task.Delay(1000);

                    Log.LogDebug($"Sending DTMF sequence {string.Join("", DTMF_SEQUENCEFOR_TRANSFEROR.Select(x => x))}.");
                    foreach (byte dtmf in DTMF_SEQUENCEFOR_TRANSFEROR)
                    {
                        Log.LogDebug($"Sending DTMF tone to target {dtmf}.");
                        await userAgent.SendDtmf(dtmf);
                    }
                });
            };

            Task.Run(() => OnKeyPress(userAgent, exitCts));

            exitCts.Token.WaitHandle.WaitOne();

            #region Cleanup.

            Log.LogInformation("Exiting...");

            //userAgent?.Hangup();

            // Give any BYE or CANCEL requests time to be transmitted.
            Log.LogInformation("Waiting 1s for calls to be cleaned up...");
            Task.Delay(1000).Wait();

            if (_sipTransport != null)
            {
                Log.LogInformation("Shutting down SIP transport...");
                _sipTransport.Shutdown();
            }

            #endregion
        }
Example #6
0
        static async Task Main()
        {
            Console.WriteLine("SIPSorcery Getting Started Demo");

            AddConsoleLogger();
            CancellationTokenSource exitCts = new CancellationTokenSource();

            var sipTransport = new SIPTransport();

            EnableTraceLogs(sipTransport);

            var userAgent = new SIPUserAgent(sipTransport, OUTBOUND_PROXY);

            userAgent.ClientCallFailed += (uac, error, sipResponse) => Console.WriteLine($"Call failed {error}.");
            userAgent.OnCallHungup     += (dialog) => exitCts.Cancel();

            var windowsAudio     = new WindowsAudioEndPoint(new AudioEncoder());
            var voipMediaSession = new VoIPMediaSession(windowsAudio.ToMediaEndPoints());

            voipMediaSession.AcceptRtpFromAny     = true;
            voipMediaSession.OnRtpPacketReceived += OnRtpPacketReceived;

            string            fromHeader     = (new SIPFromHeader(USERNAME, new SIPURI(USERNAME, DOMAIN, null), null)).ToString();
            SIPCallDescriptor callDescriptor = new SIPCallDescriptor(USERNAME, PASSWORD, DESTINATION, fromHeader, null, null, null, null, SIPCallDirection.Out, SDP.SDP_MIME_CONTENTTYPE, null, null);
            //callDescriptor.CallId = "16152412565";
            //callDescriptor.AuthUsername = USERNAME;

            // Place the call and wait for the result.
            var callTask = userAgent.Call(callDescriptor, voipMediaSession);

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;

                if (userAgent != null)
                {
                    if (userAgent.IsCalling || userAgent.IsRinging)
                    {
                        Console.WriteLine("Cancelling in progress call.");
                        userAgent.Cancel();
                    }
                    else if (userAgent.IsCallActive)
                    {
                        Console.WriteLine("Hanging up established call.");
                        userAgent.Hangup();
                        _waveFile.Dispose();
                    }
                }
                ;

                exitCts.Cancel();
            };

            Console.WriteLine("press ctrl-c to exit...");

            bool callResult = await callTask;


            if (callResult)
            {
                Console.WriteLine("Enter digits one after another");
                string meetingNo = "1711622132";
                Console.WriteLine("Enter meetingno ?");
                Console.ReadLine();
                foreach (var item in meetingNo)
                {
                    await userAgent.SendDtmf(byte.Parse(item.ToString()));

                    Console.WriteLine("Sending DTMF - " + byte.Parse(item.ToString()));
                    Thread.Sleep(2000);
                }
                Thread.Sleep(2000);
                await userAgent.SendDtmf(Encoding.ASCII.GetBytes("#")[0]);

                Thread.Sleep(13000);
                Console.WriteLine("Sending AttendeeID ?");

                /*string attendeeId = "635619";
                 * foreach (var item in attendeeId)
                 * {
                 *  await userAgent.SendDtmf(byte.Parse(item.ToString()));
                 *  Console.WriteLine("Sending DTMF - " + byte.Parse(item.ToString()));
                 *  Thread.Sleep(2000);
                 * }*/
                await userAgent.SendDtmf(Encoding.ASCII.GetBytes("#")[0]);

                Console.ReadLine();
                await userAgent.SendDtmf(Encoding.ASCII.GetBytes("#")[0]);

                Console.WriteLine($"Call to {DESTINATION} succeeded.");
                exitCts.Token.WaitHandle.WaitOne();
            }
            else
            {
                Console.WriteLine($"Call to {DESTINATION} failed.");
            }

            Console.WriteLine("Exiting...");

            if (userAgent?.IsHangingUp == true)
            {
                Console.WriteLine("Waiting 1s for the call hangup or cancel to complete...");
                await Task.Delay(1000);
            }

            // Clean up.
            sipTransport.Shutdown();
        }