[Freeswitch-svn] [commit] r9537 - in freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk: EventWatcher FreeSwitch.EventSocket.Test FreeSwitchEventSocket IvrSocket
Freeswitch SVN
verifier at freeswitch.org
Fri Sep 12 11:24:29 EDT 2008
Author: verifier
Date: Fri Sep 12 11:24:28 2008
New Revision: 9537
Added:
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/LogWriterHandler.cs
Modified:
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/ChannelWatcher.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/Form1.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitch.EventSocket.Test/EventSocket.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventManager.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventSocket.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/FreeSwitch.EventSocket.csproj
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/Program.cs
freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/IvrSocket/Program.cs
Log:
Improved documentation and added a logging delegate to let you handle logs in your favorite logging framework.
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/ChannelWatcher.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/ChannelWatcher.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/ChannelWatcher.cs Fri Sep 12 11:24:28 2008
@@ -9,7 +9,7 @@
{
public partial class ChannelWatcher : Form
{
- private EventManager _mgr = new EventManager();
+ private EventManager _mgr = new EventManager(null);
private Color _currentColor = 0;
StringBuilder sb = new StringBuilder();
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/Form1.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/Form1.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/EventWatcher/Form1.cs Fri Sep 12 11:24:28 2008
@@ -17,7 +17,7 @@
public Form1()
{
InitializeComponent();
- _eventMgr = new EventManager();
+ _eventMgr = new EventManager(null);
_callMgr = new CallManager(_eventMgr);
_callMgr.OnCallState += OnCallState;
_callMgr.ExtensionAdded += OnExtensionAdded;
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitch.EventSocket.Test/EventSocket.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitch.EventSocket.Test/EventSocket.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitch.EventSocket.Test/EventSocket.cs Fri Sep 12 11:24:28 2008
@@ -9,7 +9,7 @@
{
class EventSocket
{
- private FreeSwitch.EventSocket.EventSocket m_es = new FreeSwitch.EventSocket.EventSocket();
+ private FreeSwitch.EventSocket.EventSocket m_es = new FreeSwitch.EventSocket.EventSocket(null);
public void Setup()
{
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventManager.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventManager.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventManager.cs Fri Sep 12 11:24:28 2008
@@ -5,41 +5,71 @@
namespace FreeSwitch.EventSocket
{
+ /// <summary>
+ /// Delegate used to receive a parsed event.
+ /// </summary>
+ /// <param name="receivedEvent">the event.</param>
public delegate void EventHandler(EventBase receivedEvent);
+ /// <summary>
+ /// Delegate used to receive unparsed event messages
+ /// </summary>
+ /// <param name="text">text received from FreeSWITCH.</param>
public delegate void EventsWriter(string text);
+ /// <summary>
+ /// Takes care of the event socket and parses the incoming events.
+ /// </summary>
public class EventManager
{
- private readonly EventSocket _socket = new EventSocket();
- public event EventHandler EventReceived;
+ private readonly EventSocket _socket;
+ /// <summary>
+ /// An event have been received from freeswitch.
+ /// </summary>
+ public event EventHandler EventReceived = delegate{};
private readonly EventsWriter _writer;
- private readonly TextWriter _rawLog;
- private object _logLocker = new object();
+ private readonly object _logLocker = new object();
+ private readonly LogWriterHandler _logWriter;
+ /// <summary>
+ /// FreeSWITCH password, default is "ClueCon".
+ /// </summary>
public string Password
{
set { _socket.Password = value; }
}
- public EventManager()
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EventManager"/> class.
+ /// </summary>
+ /// <param name="logWriter">Can be used for logging.</param>
+ public EventManager(LogWriterHandler logWriter)
{
- _writer = RawWriter;
- _rawLog = new StreamWriter(new FileStream("C:\\temp\\WatcherRaw.log", FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
+ _logWriter = logWriter ?? NullWriter.Write;
+ _socket = new EventSocket(_logWriter);
+ _writer = VoidWriter;
}
- private void RawWriter(string text)
+ private static void VoidWriter(string text)
{
- _rawLog.Write(text);
- _rawLog.Flush();
}
-
- public EventManager(EventsWriter writer)
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EventManager"/> class.
+ /// </summary>
+ /// <param name="logWriter">Used to receive loggings.</param>
+ /// <param name="writer">Used to receive unparsed event messages.</param>
+ public EventManager(LogWriterHandler logWriter, EventsWriter writer)
{
+ _logWriter = logWriter ?? NullWriter.Write;
+ _socket = new EventSocket(_logWriter);
_writer = writer;
}
+ /// <summary>
+ /// Starts event manger and connect to freeswitch.
+ /// </summary>
+ /// <param name="hostname">hostname/ipaddress colon port</param>
public void Start(string hostname)
{
_socket.MessageReceived += OnMessage;
@@ -65,6 +95,10 @@
_socket.Send(cmd);
}
+ /// <summary>
+ /// Sends the SendMsg command to FreeSWITCH
+ /// </summary>
+ /// <param name="cmd">The CMD.</param>
public void Send(SendMsg cmd)
{
_socket.Send(cmd);
@@ -77,10 +111,9 @@
if (eventName == null)
return;
- if (string.Compare(parameters["event-name"], "custom", true) == 0)
- eventName = parameters["event-subclass"];
- else
- eventName = parameters["event-name"];
+ eventName = string.Compare(parameters["event-name"], "custom", true) == 0
+ ? parameters["event-subclass"]
+ : parameters["event-name"];
//Quickhack for Sofia::Register (convert to sofia_register)
eventName = eventName.Replace("::", "_");
@@ -94,51 +127,25 @@
{
eb.SetParameters(parameters);
eb.Parse(parameters);
- if (EventReceived != null)
- EventReceived(eb);
-
- /*
- EventChannelState channel = eb as EventChannelState;
- if (channel != null)
- {
- Console.WriteLine("[" + eb.Name + "/" + channel.ChannelInfo.State + "] (uid: " +
- channel.UniqueId + ")");
- Console.WriteLine(" ChannelInfo:");
- Console.WriteLine(" Name: " + channel.ChannelInfo.Name);
- Console.WriteLine(" State: " + channel.ChannelInfo.State);
- if (channel.Caller != null)
- {
- Console.WriteLine(" CallerInfo:");
- Console.WriteLine(" Id: " + channel.Caller.UniqueId);
- Console.WriteLine(" UserName: " + channel.Caller.UserName);
- Console.WriteLine(" CallerId: " + channel.Caller.CallerIdName + "/" +
- channel.Caller.CallerIdNumber);
- Console.WriteLine(" ChannelName: " + channel.Caller.ChannelName);
- Console.WriteLine(" DestinationNumber: " + channel.Caller.DestinationNumber);
- }
-
- if (channel.Originator != null)
- {
- Console.WriteLine(" Originator:");
- Console.WriteLine(" Id: " + channel.Originator.UniqueId);
- Console.WriteLine(" UserName: " + channel.Originator.UserName);
- Console.WriteLine(" CallerId: " + channel.Originator.CallerIdName + "/" +
- channel.Originator.CallerIdNumber);
- Console.WriteLine(" ChannelName: " + channel.Originator.ChannelName);
- Console.WriteLine(" DestinationNumber: " + channel.Originator.DestinationNumber);
- }
- }
- //}*/
+ EventReceived(eb);
}
else
- Console.WriteLine("* Failed to load '" + eventName + "'.");
+ _logWriter(LogPrio.Warning, "Failed to load '" + eventName + "'.");
}
+ /// <summary>
+ /// Subscribes the specified events.
+ /// </summary>
+ /// <param name="events">The events.</param>
public void Subscribe(Events events)
{
_socket.Subscribe(events);
}
+ /// <summary>
+ /// Subscribes the specified events.
+ /// </summary>
+ /// <param name="events">The events.</param>
public void Subscribe(params Event[] events)
{
_socket.Subscribe(new Events(events));
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventSocket.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventSocket.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/EventSocket.cs Fri Sep 12 11:24:28 2008
@@ -20,6 +20,7 @@
#endregion
+ private LogWriterHandler _logWriter;
private readonly Queue<CmdBase> _commands = new Queue<CmdBase>();
private bool _autoConnect = true;
private Events _events;
@@ -33,12 +34,17 @@
private Socket _socket;
private NetworkStream _stream;
private Timer _timer;
- private bool _authed = false;
+ private bool _authed;
const int RetryTimeout = 5000;
- private bool _parsing = false;
+ private bool _parsing;
- public EventSocket()
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EventSocket"/> class.
+ /// </summary>
+ /// <param name="logWriter">The log writer.</param>
+ public EventSocket(LogWriterHandler logWriter)
{
+ LogWriter = logWriter ?? NullWriter.Write;
CreateSocket();
}
@@ -49,23 +55,55 @@
_socket.ReceiveBufferSize = 65535;
}
+ /// <summary>
+ /// Used to authenticate towards FreeSWITCH.
+ /// </summary>
+ /// <remarks>
+ /// Default is "ClueCon"
+ /// </remarks>
public string Password
{
get { return _password; }
set { _password = value; }
}
+ /// <summary>
+ /// Connect automatically again if socket is disconnected.
+ /// </summary>
public bool AutoConnect
{
get { return _autoConnect; }
set { _autoConnect = value; }
}
- public event MessageHandler MessageReceived;
+ public LogWriterHandler LogWriter
+ {
+ get { return _logWriter; }
+ set { _logWriter = value ?? NullWriter.Write; }
+ }
+
+ /// <summary>
+ /// A event have been received
+ /// </summary>
+ public event MessageHandler MessageReceived = delegate{};
+
+ /// <summary>
+ /// Socket got disconnected (due to remote peer)
+ /// </summary>
+ public event EventSocketHandler Disconnected = delegate{};
- public event EventSocketHandler Disconnected;
- public event EventSocketHandler Connected;
+ /// <summary>
+ /// Socket is now connected
+ /// </summary>
+ public event EventSocketHandler Connected = delegate{};
+ /// <summary>
+ /// Connect to FreeSWITCH
+ /// </summary>
+ /// <param name="server">hostname/ipaddress colon port</param>
+ /// <example>
+ /// <code>eventSocket.Connect("localhost:1234");</code>
+ /// </example>
public void Connect(string server)
{
int pos = server.IndexOf(':');
@@ -80,6 +118,9 @@
Connect();
}
+ /// <summary>
+ /// Connect to the previously specified host.
+ /// </summary>
public void Connect()
{
if (_hostName == null)
@@ -88,9 +129,11 @@
try
{
TryConnect();
+ LogWriter(LogPrio.Debug, "Connected to freeswitch.");
}
- catch (SocketException)
+ catch (SocketException err)
{
+ LogWriter(LogPrio.Debug, "Failed to connect to freeswitch, reason: " + err.Message);
HandleDisconnect();
}
}
@@ -103,17 +146,14 @@
if (_stream == null)
_stream = new NetworkStream(_socket, false);
- if (Connected != null)
- Connected(this);
+ Connected(this);
BeginRead();
- if (_timer != null)
- {
- Timer tmr = _timer;
- _timer = null;
- tmr.Change(Timeout.Infinite, Timeout.Infinite);
- tmr.Dispose();
- }
+ if (_timer == null) return;
+ Timer tmr = _timer;
+ _timer = null;
+ tmr.Change(Timeout.Infinite, Timeout.Infinite);
+ tmr.Dispose();
}
}
@@ -133,6 +173,7 @@
int bytesRead = _stream.EndRead(ar);
if (bytesRead == 0)
{
+ LogWriter(LogPrio.Error, "Got disconnected (0 bytes read).");
HandleDisconnect();
return;
}
@@ -140,27 +181,29 @@
_parser.Append(inbuffer);
BeginRead();
}
- catch (IOException)
+ catch (IOException err)
{
+ LogWriter(LogPrio.Debug, "IO exception during read: " + err.Message);
// Remote end disconnected.
HandleDisconnect();
return;
}
- if (DataReceived != null && !string.IsNullOrEmpty(inbuffer))
+ if (!string.IsNullOrEmpty(inbuffer))
DataReceived(inbuffer);
try
{
ParseMessages();
}
- catch (InvalidDataException)
+ catch (InvalidDataException err)
{
+ LogWriter(LogPrio.Warning, "Failed to parse event message (" + err.Message + "): " + Environment.NewLine + _parser.Text);
HandleDisconnect();
}
- catch (ArgumentException)
+ catch (ArgumentException err)
{
- Console.WriteLine(_parser.Text);
+ LogWriter(LogPrio.Warning, "Failed to parse event message ("+err.Message+"): " + Environment.NewLine + _parser.Text);
HandleDisconnect();
}
}
@@ -191,6 +234,7 @@
try
{
TryConnect();
+ LogWriter(LogPrio.Info, "We've connected again");
}
catch (SocketException)
{
@@ -216,37 +260,35 @@
try
{
PlainEventMsg msg = _parser.ParseOne();
+ LogWriter(LogPrio.Trace, "MessageType: " + msg.ContentType);
while (msg != null)
{
- if (msg.ContentType == "auth/request")
- {
- AuthCommand cmd = new AuthCommand(_password);
- cmd.ReplyReceived += OnAuthed;
- _commands.Enqueue(cmd);
- Write(cmd + "\n\n");
- }
- else if (msg.ContentType == "command/reply"
- || msg.ContentType == "api/response")
- {
- if (_commands.Count > 0)
- {
- CmdBase cmd = _commands.Dequeue();
- cmd.HandleReply(cmd.CreateReply(msg.Body.Trim()));
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Got command reply or api response, but no actual command/api: " + msg.Body);
- Console.ForegroundColor = ConsoleColor.Gray;
- }
- }
- else
+ switch (msg.ContentType)
{
- if (MessageReceived != null)
+ case "auth/request":
+ {
+ AuthCommand cmd = new AuthCommand(_password);
+ cmd.ReplyReceived += OnAuthed;
+ _commands.Enqueue(cmd);
+ Write(cmd + "\n\n");
+ }
+ break;
+ case "api/response":
+ case "command/reply":
+ if (_commands.Count > 0)
+ {
+ CmdBase cmd = _commands.Dequeue();
+ cmd.HandleReply(cmd.CreateReply(msg.Body.Trim()));
+ }
+ else
+ LogWriter(LogPrio.Debug, "Got command reply or api response, but no actual command/api: " + msg.Body);
+ break;
+ default:
MessageReceived(msg);
+ break;
}
msg = _parser.ParseOne();
- }
+ }
}
finally
{
@@ -257,6 +299,7 @@
private void OnAuthed(CmdBase command, CommandReply reply)
{
+ LogWriter(LogPrio.Trace, "We have not authenticated.");
_authed = true;
RequestEvents();
}
@@ -273,13 +316,10 @@
_stream = null;
}
- if (Disconnected != null)
- Disconnected.Invoke(this);
- if (AutoConnect && _timer == null)
- {
- Console.WriteLine("EventSocket: Launching timer.");
- _timer = new Timer(TryConnect, this, RetryTimeout, RetryTimeout);
- }
+ Disconnected(this);
+ if (!AutoConnect || _timer != null) return;
+ LogWriter(LogPrio.Info, "Launching autoconnect timer.");
+ _timer = new Timer(TryConnect, this, RetryTimeout, RetryTimeout);
}
private void RequestEvents()
@@ -309,7 +349,10 @@
public void Send(CmdBase command)
{
if (!_socket.Connected)
+ {
+ LogWriter(LogPrio.Debug, "Tried to send command when we are not connected: " + command);
throw new IOException("Socket is not connected.");
+ }
_commands.Enqueue(command);
@@ -317,13 +360,13 @@
Write(command + "\n\n");
}
- private static void TryConnect(object state)
+ private void TryConnect(object state)
{
EventSocket client = (EventSocket) state;
try
{
client.TryConnect();
- Console.WriteLine("EventSocket.Timer: Connected.");
+ LogWriter(LogPrio.Info, "Connected again.");
}
catch (SocketException)
{}
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/FreeSwitch.EventSocket.csproj
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/FreeSwitch.EventSocket.csproj (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/FreeSwitch.EventSocket.csproj Fri Sep 12 11:24:28 2008
@@ -74,6 +74,7 @@
<Compile Include="Ivr\IvrInterface.cs" />
<Compile Include="Ivr\IvrQueue.cs" />
<Compile Include="Ivr\PrivateWaitDtmf.cs" />
+ <Compile Include="LogWriterHandler.cs" />
<Compile Include="PlainEventMsg.cs" />
<Compile Include="EventParser.cs" />
<Compile Include="Events.cs" />
Added: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/LogWriterHandler.cs
==============================================================================
--- (empty file)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/LogWriterHandler.cs Fri Sep 12 11:24:28 2008
@@ -0,0 +1,59 @@
+namespace FreeSwitch.EventSocket
+{
+ /// <summary>
+ /// Determines how important the log message is.
+ /// </summary>
+ public enum LogPrio
+ {
+ /// <summary>
+ /// Not important at all, used to follow the flow of the program
+ /// </summary>
+ Trace,
+
+ /// <summary>
+ /// Messages useful when debugging
+ /// </summary>
+ Debug,
+
+ /// <summary>
+ /// States etc have changed.
+ /// </summary>
+ Info,
+
+ /// <summary>
+ /// Something did not go as we expected, but we can handle it.
+ /// </summary>
+ Warning,
+
+ /// <summary>
+ /// Something went wrong, we can't really handle it, but the program can continue to live
+ /// </summary>
+ Error,
+
+ /// <summary>
+ /// Some went really wrong, and the program should really be shut down.
+ /// </summary>
+ Fatal
+ }
+
+ /// <summary>
+ /// Used to retreive logging messages from the event socket framework.
+ /// </summary>
+ /// <param name="prio">importance of the log message</param>
+ /// <param name="message">the message</param>
+ public delegate void LogWriterHandler(LogPrio prio, string message);
+
+ /// <summary>
+ /// Used as default logwriter
+ /// </summary>
+ internal class NullWriter
+ {
+ /// <summary>
+ /// Used to log to void.
+ /// </summary>
+ /// <param name="prio"></param>
+ /// <param name="message"></param>
+ public static void Write(LogPrio prio, string message)
+ {}
+ }
+}
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/Program.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/Program.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/FreeSwitchEventSocket/Program.cs Fri Sep 12 11:24:28 2008
@@ -25,7 +25,7 @@
Program p = new Program();
/// Create a new FreeSwitch event socket.
- EventManager eventManager = new EventManager();
+ EventManager eventManager = new EventManager(null);
// Hook all events to the same delegate. Can also provide one delegate per event.
eventManager.EventReceived += p.HandleEvent;
Modified: freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/IvrSocket/Program.cs
==============================================================================
--- freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/IvrSocket/Program.cs (original)
+++ freeswitch/trunk/scripts/contrib/verifier/EventSocket/trunk/IvrSocket/Program.cs Fri Sep 12 11:24:28 2008
@@ -10,7 +10,7 @@
private static EventManager mgr;
static void Main(string[] args)
{
- mgr = new EventManager();
+ mgr = new EventManager(null);
mgr.EventReceived += IvrManager;
mgr.Subscribe(Event.All);
mgr.Start("localhost");
More information about the Freeswitch-svn
mailing list