/// <summary> /// Plays the given file to the specified channel. /// </summary> /// <param name="eventSocket">The EventSocket instance.</param> /// <param name="uuid">The Channel UUID.</param> /// <param name="file">The Path to the file to be played. Note: use forward slashes for path separators.</param> /// <param name="options">Options to customize playback.</param> /// <returns>A PlayResult.</returns> /// <exception cref="FileNotFoundException">Throws FileNotFoundException if FreeSwitch is unable to play the file.</exception>//todo: should it? public static async Task <PlayResult> Play(this EventSocket eventSocket, string uuid, string file, PlayOptions options = null) { // todo: implement options for playback eg a-leg, b-leg, both, using uuid_displace if (options == null) { options = new PlayOptions(); } try { // todo: what if applicationresult is null (hang up occurs before the application completes) var result = new PlayResult( await eventSocket.ExecuteApplication(uuid, "playback", file, loops: options.Loops) .ConfigureAwait(false)); if (!result.Success) { LogFailedApplicationResult(eventSocket, result); } return(result); } catch (TaskCanceledException ex) { return(new PlayResult(null)); } }
protected BasicChannel(EventMessage eventMessage, EventSocket eventSocket) { Log = LogProvider.GetLogger(GetType()); UUID = eventMessage.UUID; lastEvent = eventMessage; this.eventSocket = eventSocket; Disposables.Add( eventSocket.Events .Where(x => x.UUID == UUID) .Subscribe( e => { lastEvent = e; if (e.EventName == EventName.ChannelAnswer) { Log.Info(() => "Channel [{0}] Answered".Fmt(UUID)); } if (e.EventName == EventName.ChannelHangup) { Log.Info(() => "Channel [{0}] Hangup Detected [{1}]".Fmt(UUID, e.HangupCause)); HangupCallBack(e); } })); }
public void websocket_Opened(object sender, EventArgs e) { isDisConect = false; EventSocket eSocket = new EventSocket(ActionTicket.CONNECT); DataReceived(eSocket); }
public static Task <CommandReply> SendEvent( this EventSocket eventSocket, string eventName, IDictionary <string, string> headers = null) { if (eventName == null) { throw new ArgumentNullException("eventName"); } if (headers == null) { headers = new Dictionary <string, string>(); } var headersString = headers.Aggregate( StringBuilderPool.Allocate(), (sb, kvp) => { sb.AppendFormat("{0}: {1}", kvp.Key, kvp.Value); sb.Append("\n"); return(sb); }, StringBuilderPool.ReturnAndFree); return(eventSocket.SendCommand("sendevent {0}\n{1}".Fmt(eventName, headersString))); }
private static async Task <OriginateResult> InternalOriginate(EventSocket socket, string endpoint, string destination, OriginateOptions options = null) { if (options == null) { options = new OriginateOptions(); } // if no UUID provided, we'll set one now and use that to filter for the correct channel events // this way, one inbound socket can originate many calls and we can complete the correct // TaskCompletionSource for each originated call. if (string.IsNullOrEmpty(options.UUID)) { options.UUID = Guid.NewGuid().ToString(); } await socket.SubscribeEvents(EventName.ChannelAnswer, EventName.ChannelHangup, EventName.ChannelProgress).ConfigureAwait(false); var originateString = string.Format("{0}{1} {2}", options, endpoint, destination); return (await socket.BackgroundJob("originate", originateString) .ToObservable() .Merge( socket.ChannelEvents.FirstAsync( x => x.UUID == options.UUID && (x.EventName == EventName.ChannelAnswer || x.EventName == EventName.ChannelHangup || (options.ReturnRingReady && x.EventName == EventName.ChannelProgress))).Cast <BasicMessage>()) .FirstAsync(x => (x is BackgroundJobResult && !((BackgroundJobResult)x).Success) || x is ChannelEvent) .Select(OriginateResult.FromBackgroundJobResultOrChannelEvent) // pattern matching, my kingdom for pattern matching .ToTask() .ConfigureAwait(false)); }
protected Channel(EventMessage eventMessage, EventSocket eventSocket) : base(eventMessage, eventSocket) { eventSocket.SubscribeEvents(EventName.ChannelCreate).Wait(); Disposables.Add( eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelBridge).Subscribe( x => { Log.Trace(() => "Channel [{0}] Bridged to [{1}]".Fmt(UUID, x.GetHeader(HeaderNames.OtherLegUniqueId))); if (Bridge.Channel != null && x.GetHeader(HeaderNames.OtherLegUniqueId) != Bridge.Channel.UUID) { //possibly changed bridge partner as part of att_xfer Log.Warn(() => "Channel [{0}] was Bridged to [{1}] but now changed to [{2}]".Fmt(UUID, Bridge.Channel.UUID, x.UUID)); Bridge.Channel.Dispose(); Bridge = new BridgeStatus(true, "TRANSFERRED", new BridgedChannel(x, eventSocket)); } })); Disposables.Add( eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelUnbridge).Subscribe( x => Log.Trace(() => "Channel [{0}] Unbridged from [{1}] {2}".Fmt(UUID, Bridge.Channel.UUID, x.GetVariable("bridge_hangup_cause"))))); Disposables.Add( eventSocket.Events.Where(x => x.EventName == EventName.ChannelBridge && x.UUID != UUID && x.GetHeader(HeaderNames.OtherLegUniqueId) == UUID && (Bridge.Channel != null && x.UUID != Bridge.Channel.UUID)) .Subscribe(x => { //there is another channel out there that has bridged to us but we didn't get the CHANNEL_BRIDGE event on this channel //possibly an attended transfer. We'll swap our bridge partner so we can get its events Log.Warn(() => "Channel [{0}] was Bridged to [{1}] but now changed to [{2}]".Fmt(UUID, Bridge.Channel.UUID, x.UUID)); Bridge.Channel.Dispose(); Bridge = new BridgeStatus(true, "TRANSFERRED", new BridgedChannel(x, eventSocket)); })); if (this.eventSocket is OutboundSocket) { Disposables.Add( eventSocket.Events.Where(x => x.UUID == UUID && x.EventName == EventName.ChannelHangup) .Subscribe(async e => { if (ExitOnHangup) { await eventSocket.Exit(); Log.Info(() => "Channel [{0}] exited".Fmt(UUID)); } })); } //populate empty bridge status Bridge = new BridgeStatus(false, null); ExitOnHangup = true; }
/// <summary> /// Originate a new call. /// </summary> /// <remarks> /// See https://freeswitch.org/confluence/display/FREESWITCH/mod_commands#mod_commands-originate /// </remarks> /// <param name="socket">the <seealso cref="EventSocket"/> instance.</param> /// <param name="endpoint">The destination to call.</param> /// <param name="options">(Optional) <seealso cref="OriginateOptions" /> to configure the call.</param> /// <param name="application">(Default: park) The DialPlan application to execute on answer</param> /// <returns>A Task of <seealso cref="OriginateResult" />.</returns> public static Task <OriginateResult> Originate( this EventSocket socket, string endpoint, OriginateOptions options = null, string application = "park", string applicationArgs = null) { return(InternalOriginate(socket, endpoint, string.Format("'&{0}({1})'", application, applicationArgs), options)); }
/// <summary> /// Send an api command (blocking mode) /// </summary> /// <remarks> /// See https://freeswitch.org/confluence/display/FREESWITCH/mod_event_socket#mod_event_socket-api /// </remarks> /// <param name="eventSocket">The EventSocket instance to execute on.</param> /// <param name="command">The API command to send (see https://wiki.freeswitch.org/wiki/Mod_commands) </param> /// <param name="arg">(Optional) any arguments for the api command.</param> /// <returns>A Task of <seealso cref="ApiResponse"/>.</returns> public static Task <ApiResponse> Api(this EventSocket eventSocket, string command, string arg = null) { if (command == null) { throw new ArgumentNullException("command"); } return(eventSocket.SendApi(arg != null ? "{0} {1}".Fmt(command, arg) : command)); }
public SocketClientWorker() { // Init socket Client = new EventSocket(SocketType.Stream, ProtocolType.Tcp); SocketThread = Thread.CurrentThread; // Sub events _worker.DoWork += _worker_DoWork; }
public static Task <CommandReply> FilterDelete(this EventSocket eventSocket, string header) { if (header == null) { throw new ArgumentNullException("header"); } return(eventSocket.SendCommand("filter delete {0}".Fmt(header))); }
private static void LogFailedApplicationResult(EventSocket eventSocket, ApplicationResult result) { if (result.ChannelData != null) { Console.WriteLine("Application {0} {1} failed - {2}".Fmt( result.ChannelData.Headers[HeaderNames.Application], result.ChannelData.Headers[HeaderNames.ApplicationData], result.ChannelData.Headers[HeaderNames.ApplicationResponse])); } }
/// <summary> /// Create a new connection and start connecting /// </summary> /// <param name="host">The host to connect to</param> /// <param name="port">The port to use</param> public Connection(string host, int port) { Socket = new EventSocket(host, port); Socket.OnData += Socket_OnData; Socket.OnError += Socket_OnError; Socket.OnClose += Socket_OnClose; Socket.OnConnect += Socket_OnConnect; LastReceivedId = 0; LastSentId = 0; }
/// <summary> /// Originate a new call /// </summary> /// <remarks> /// See https://freeswitch.org/confluence/display/FREESWITCH/mod_commands#mod_commands-originate /// </remarks> /// <param name="socket">the <seealso cref="EventSocket"/> instance.</param> /// <param name="endpoint">The destination to call.</param> /// <param name="extension">Destination number to search in dialplan</param> /// <param name="dialplan">(Optional) defaults to 'XML' if not specified</param> /// <param name="context">(Optional) defaults to 'default' if not specified</param> /// <param name="options">(Optional) <seealso cref="OriginateOptions" /> to configure the call.</param> /// <returns>A Task of <seealso cref="OriginateResult" />.</returns> public static Task <OriginateResult> Originate( this EventSocket socket, string endpoint, string extension, string dialplan = "XML", string context = "default", OriginateOptions options = null) { return(InternalOriginate(socket, endpoint, string.Format("{0} {1} {2}", extension, dialplan, context), options)); }
private void sendNotiTicket(Ticket tk) { foreach (var cou in dicAllCounters.Values) { if (cou.isNoTicket && cou.Services.Any(m => m == tk.Services[0])) { cou.isNoTicket = false; EventSocket eSocket = new EventSocket(ActionTicket.ACTION_CREATE, cou.Id); DataReceived(eSocket); } } }
protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { Socket.Dispose(); } Socket = null; } }
public static Task <CommandReply> Hangup( this EventSocket eventSocket, string uuid, HangupCause hangupCause = HangupCause.NormalClearing) { if (uuid == null) { throw new ArgumentNullException("uuid"); } return (eventSocket.SendCommand( "sendmsg {0}\ncall-command: hangup\nhangup-cause: {1}".Fmt(uuid, hangupCause.ToString().ToUpperWithUnderscores()))); }
private Reptile() { var mem = new MatchEntityManager(); mem.Init(this); matchEntityManager = mem; IocUnity.RegisterInstance("MatchEntityManager", matchEntityManager); socket = new EventSocket(); socket.SocketSink = this; socket.ServerIP = ConfigSingleton.CreateInstance().GetAppConfig <string>("ServerIP"); socket.ServerPort = ConfigSingleton.CreateInstance().GetAppConfig <ushort>("ServerPort"); }
private void sendDataToSocket(string data) { if (webSocket == null) { EventSocket eSocket = new EventSocket(ActionTicket.DISCONNECT); DataReceived(eSocket); SetTimer(); } else { this.webSocket.Send(data); } }
private static void LogFailedApplicationResult(EventSocket eventSocket, ApplicationResult result) { if (result.ChannelData != null) { LogProvider.GetLogger(eventSocket.GetType()) .Error( () => "Application {0} {1} failed - {2}".Fmt( result.ChannelData.Headers[HeaderNames.Application], result.ChannelData.Headers[HeaderNames.ApplicationData], result.ChannelData.Headers[HeaderNames.ApplicationResponse])); } }
public static Task <CommandReply> Filter(this EventSocket eventSocket, string header, string value) { if (header == null) { throw new ArgumentNullException("header"); } if (value == null) { throw new ArgumentNullException("value"); } return(eventSocket.SendCommand("filter {0} {1}".Fmt(header, value))); }
/// <summary> /// Set Multiple Channel Variables in one go /// </summary> /// <remarks> /// See https://wiki.freeswitch.org/wiki/Mod_commands#uuid_setvar_multi /// </remarks> /// <param name="eventSocket">The EventSocket instance.</param> /// <param name="uuid">The Channel UUID.</param> /// <param name="assignments">Array of assignments in the form "foo=value", "bar=value".</param> /// <returns>A Task of <seealso cref="ApiResponse"/> representing the CHANNEL_EXECUTE_COMPLETE event.</returns> public static Task <ApiResponse> SetMultipleChannelVariables(this EventSocket eventSocket, string uuid, params string[] assignments) { return(eventSocket.SendApi( "uuid_setvar_multi {0} {1}".Fmt( uuid, assignments.Aggregate( StringBuilderPool.Allocate(), (sb, s) => { sb.Append(s); sb.Append(";"); return sb; }, StringBuilderPool.ReturnAndFree)))); }
public void websocket_Closed(object sender, EventArgs e) { while (this.webSocket != null && this.webSocket.State == WebSocketState.Closed && !isDisConect) { if (!isReload) { isDisConect = true; EventSocket eSocket = new EventSocket(ActionTicket.DISCONNECT); DataReceived(eSocket); } OpendSocket(); Thread.Sleep(200); } }
private static void InitKeyBoardSend(EventSocket eventData) { if (eventData.IsLoadService) { dicService = sortDicServices(eventData.DicService); List <string> lstServices = dicService.Values.OrderBy(m => m.NameService).Select(m => m.NameService).ToList(); EventProgram ev = new EventProgram(ActionTicket.INITIAL_SER, null, lstServices); serialCtrl.SendKeyBoard(ev); Thread.Sleep(5000); } #region SET SERVICE COUNTER CHO DEVICE // send Counter if (eventData.IsLoadCounter) { dicCounter = sortDicCounter(eventData.DicCounter); foreach (var item in config.KeyBoardCounters) { int address = item.AddressKeyboard; int numCounter = item.NumCounter; var cou = dicCounter.Values.FirstOrDefault(m => m.CNum == numCounter); if (cou != null && !string.IsNullOrWhiteSpace(cou.Id)) { item.CounterID = cou.Id; dicCounterKeyboard[address] = item; } } } List <string> lstCounters = dicCounter.Values.Select(m => m.Name).ToList(); //EventProgram evCou = new EventProgram(ActionTicket.INITIAL_COU, 1, lstCounters);// fix 1 = mấy đều được //serialCtrl.SendKeyBoard(evCou); EventProgram evCou1 = new EventProgram(ActionTicket.INITIAL_COU, eventData.DicCounter.Values.OrderBy(m => m.CNum).ToList(), dicCounterKeyboard);// fix 1 = mấy đều được serialCtrl.SendKeyBoard(evCou1); Thread.Sleep(5000); //Set lai data cho recive port serialCtrl.SetDataRecive(dicService, dicCounter, dicCounterKeyboard); Thread.Sleep(1800); #endregion //send Led inital var evReset = new EventProgram(ActionTicket.ACTION_RESET); serialCtrl.SendKeyBoard(evReset); Thread.Sleep(100); SendNumToCounter(eventData, false); Console.WriteLine("Set services and counter success!"); }
public void Received(string str) { var handle = str.Split(' ')[0].Trim('/'); var data = str.Remove(0, str.IndexOf(' ')); try { switch (handle) { case ActionTicket.INITIAL: Initial dataUser = JsonConvert.DeserializeObject <Initial>(data); var dicSerNew = socController.setDicServices(dataUser.Services, new Dictionary <string, Service>(), config.LangCd); var dicCouNew = socController.setDicCounters(dataUser.Counters, new Dictionary <string, Counter>(), config.LangCd); var arrCheck = socController.CheckModifyServiceCounter(dicAllCounters, dicAllServices, dicCouNew, dicSerNew); initParam(); dicAllCounters = dicCouNew; dicAllServices = dicSerNew; SetDataToDic(dataUser.Tickets); EventSocket eSocket = new EventSocket(ActionTicket.INITIAL, dicAllServices, dicAllCounters, dicServing, arrCheck[0], arrCheck[1]); DataReceived(eSocket); break; case ActionTicket.TICKET_ACTION: var tkAc = JsonConvert.DeserializeObject <TicketAction>(data); addDic(tkAc.Action, tkAc.Ticket, tkAc.Counter_Id, tkAc.Extra); break; case ActionTicket.RELOAD: isReload = true; SetThreadExecutionState(ActionTicket.ES_CONTINUOUS); CloseSocket(); Thread.Sleep(100); break; default: break; } } catch (Exception ex) { Console.WriteLine("Loi send data" + ex.Message); } }
private static async Task <OriginateResult> InternalOriginate(EventSocket socket, string endpoint, string destination, OriginateOptions options = null) { if (options == null) { options = new OriginateOptions(); } var originateString = $"{options}{endpoint} {destination}"; await socket.SubscribeEvents(EventName.BackgroundJob).ConfigureAwait(false); return (await socket.BackgroundJob("originate", originateString) .ToObservable() .Select(OriginateResult.FromBackgroundJobResultOrChannelEvent) .ToTask() .ConfigureAwait(false)); }
/// <summary> /// Starts the listening process. /// </summary> public void Start() { try { _mainSocket = new EventSocket(SocketType.Stream, ProtocolType.Tcp); int backlog = 10; // Set the socket to listen to the local endpoint. _mainSocket.Bind(_endpoint); _mainSocket.Listen(backlog); OnStarted(backlog, _endpoint); _worker.RunWorkerAsync(); } catch (SocketException ex) { OnError(ex); } }
private static void SendNumToCounter(EventSocket eventData, bool isOpened) { bool isLst = false; if (eventData.LstSend != null && eventData.LstSend.Count() > 0) { isLst = true; foreach (var obj in eventData.LstSend) { var addKeyBoard = dicCounterKeyboard.Values.FirstOrDefault(m => m.CounterID == obj.Counter_Id); if (addKeyBoard != null) { int address = addKeyBoard.AddressKeyboard; if (address != 0) { var counterID = addKeyBoard.CounterID; var indexService = getIndexService(socket.GetService(obj), counterID); var data = obj.CNum; EventProgram ev = new EventProgram("call_hst", address, counterID, data, indexService); serialCtrl.SendKeyBoard(ev); Thread.Sleep(1000); serialCtrl.SendLED(eventData.Action, address, data); } } } } if (isOpened && isLst) { var lstCounterId = eventData.LstSend.Select(m => m.Counter_Id); var dicOut = dicCounterKeyboard.Where(m => !lstCounterId.Contains(m.Value.CounterID)); if (dicOut != null && dicOut.Count() > 0) { foreach (var item in dicOut) { EventProgram ev = new EventProgram(ActionTicket.MESSAGE_ERROR, item.Key, item.Value.CounterID, MessageError.ERROR_09, 0); serialCtrl.SendKeyBoard(ev); } } } }
public static async Task <ReadResult> Read(this EventSocket eventSocket, string uuid, ReadOptions options) { try { // todo: what if applicationresult is null (hang up occurs before the application completes) var result = new ReadResult( await eventSocket.ExecuteApplication(uuid, "read", options.ToString()).ConfigureAwait(false), options.ChannelVariableName); if (!result.Success) { LogFailedApplicationResult(eventSocket, result); } return(result); } catch (TaskCanceledException ex) { return(new ReadResult(null, null)); } }
protected BasicChannel(ChannelEvent eventMessage, EventSocket eventSocket) { Log = Logger.Get<BasicChannel>(); Uuid = eventMessage.UUID; lastEvent = eventMessage; this.eventSocket = eventSocket; Variables = new ChannelVariables(this); Disposables.Add( eventSocket.ChannelEvents .Where(x => x.UUID == Uuid) .Subscribe( e => { lastEvent = e; if (e.EventName == EventName.ChannelAnswer) { Log.LogInformation("Channel [{0}] Answered".Fmt(Uuid)); } if (e.EventName == EventName.ChannelHangupComplete) { Log.LogInformation("Channel [{0}] Hangup Detected [{1}]".Fmt(Uuid, e.HangupCause)); try { HangupCallBack(e); } catch (Exception ex) { Log.LogError(ex, "Channel [{0}] error calling hangup callback".Fmt(Uuid)); } Dispose(); } })); }
protected BasicChannel(ChannelEvent eventMessage, EventSocket eventSocket) { Log = LogProvider.GetLogger(GetType()); UUID = eventMessage.UUID; lastEvent = eventMessage; this.eventSocket = eventSocket; Variables = new ChannelVariables(this); Disposables.Add( eventSocket.ChannelEvents .Where(x => x.UUID == UUID) .Subscribe( e => { lastEvent = e; if (e.EventName == EventName.ChannelAnswer) { Log.Info(() => "Channel [{0}] Answered".Fmt(UUID)); } if (e.EventName == EventName.ChannelHangupComplete) { Log.Info(() => "Channel [{0}] Hangup Detected [{1}]".Fmt(UUID, e.HangupCause)); try { HangupCallBack(e); } catch (Exception ex) { Log.ErrorException("Channel [{0}] error calling hangup callback".Fmt(UUID), ex); } Dispose(); } })); }
private void init_us() { if (is_inited) return; is_inited = true; try { if (!System.IO.File.Exists("conf/freeswitch.xml")) { MessageBox.Show("conf/freeswitch.xml is not found, without it we must quit.", "Missing Base Configuration File", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(-1); } if (System.IO.File.Exists("log/freeswitch.log")) { try { System.IO.File.WriteAllText("log/freeswitch.log", ""); } catch (System.IO.IOException e) { MessageBox.Show( "Unable to truncate freeswitch.log (most likely due to FSCLient already running) due to: " + e.Message, "Truncation Error", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(-1); } } Account.LoadSettings(); recordings_folder = Properties.Settings.Default.RecordingPath; IncomingBalloons = Properties.Settings.Default.IncomingBalloons; IncomingTopMost = Properties.Settings.Default.FrontOnIncoming; ClearDTMFS = Properties.Settings.Default.ClearDTMFS; UseNumberOnlyInput = Properties.Settings.Default.UseNumberOnlyInput; CheckForUpdates = Properties.Settings.Default.CheckForUpdates; if (Properties.Settings.Default.Sofia != null) sofia = Properties.Settings.Default.Sofia.GetSofia(); else sofia = new Sofia(); if (Properties.Settings.Default.HeadsetPlugins != null) headset_plugin_manager = HeadsetPluginManager.GetPluginManager(Properties.Settings.Default.HeadsetPlugins); else headset_plugin_manager = new HeadsetPluginManager(); headset_plugin_manager.LoadPlugins(); if (Properties.Settings.Default.EventSocket != null) event_socket = Properties.Settings.Default.EventSocket.GetEventSocket(); else event_socket = new EventSocket(); } catch (Exception e) { MessageBoxResult res = MessageBox.Show( "Unable to properly load our settings if you continue existing settings may be lost, do you want to continue?(No to exit)\n" + e.Message, "Error Loading Settings", MessageBoxButton.YesNo); if (res != MessageBoxResult.Yes) Environment.Exit(-1); } Thread t = new Thread(init_freeswitch); t.IsBackground = true; t.Start(); t = new Thread(VersionCheck); t.IsBackground = true; t.Start(); }
protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) Socket.Dispose(); Socket = null; } }
void Socket_OnData(object sender, EventSocket.DataEventArgs args) { // Store the data Cache.Concat(args.Data); // Try to read messages while (true) { int length; BufferView backup = new BufferView(Cache); try { // Extract the size of the message length = (int)InflateData.ReadUint(Cache); } catch (Exception e) { if (!(e is InflateData.NotEnoughData)) ProtocolError(); break; } if (Cache.Length < length) { Cache = backup; break; } ProcessMessage(Cache.ExtractSlice(length)); } }
void Socket_OnError(object sender, EventSocket.ExceptionEventArgs e) { try { if (OnError == null) throw e.Data; OnError(this, e); } finally { Dispose(true); } }