Exemple #1
0
        private void CallbackTRACEDONE(object state, bool timedOut)
        {
            if (_POLLDATA.HandleWAIT != null)
            {
                _POLLDATA.HandleWAIT.Unregister(null); _POLLDATA.HandleWAIT = null;
            }                                                                                                        // Stop future execution of the callback method
            if (_POLLDATA.HandleDONE != null)
            {
                _POLLDATA.HandleDONE.Unregister(null); _POLLDATA.HandleDONE = null;
            }                                                                                                        // Stop future execution of the callback method

            if (timedOut && OnError.GetInvocationList().Length > 0)
            {
                OnError(this, new Exception("Capture Failed! Timed Out."));
            }
            else
            {
                byte[] data = _POLLDATA.GetDataQ();

                // throw event
                if (OnTraceDataIn.GetInvocationList().Length > 0)
                {
                    OnTraceDataIn(this, data);
                }
            }
        }
Exemple #2
0
        private void DisconnectCallback(IAsyncResult ar)
        {
            // Retrieve the socket from the state object.
            Socket socket = (Socket)ar.AsyncState;

            try
            {
                // Complete the disconnect.
                socket.EndDisconnect(ar);
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }

            // Signal that the disconnect is complete.
            _disconnectDone.Set();

            // Bubble the event
            if (OnDisconnected.GetInvocationList().Length > 0)
            {
                OnDisconnected(this, _socket.Connected);
            }
        }
Exemple #3
0
        private void SendCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the client socket from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;

            try
            {
                // Complete sending the data to the remote device.
                int bytesSent = state.WorkSocket.EndSend(ar);

                // Signal that all bytes have been sent.
                _sendDone.Set();

                // Bubble the event
                if (OnDataSent.GetInvocationList().Length > 0)
                {
                    OnDataSent(this, state.TextSent);
                }
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }
        }
Exemple #4
0
 private void CallbackHARTBEAT(object state, bool timedOut)
 {
     if (_RESPONSE.Handle != null)
     {
         _RESPONSE.Handle.Unregister(null); _RESPONSE.Handle = null;
     }                                                                                            // Stop future execution of the callback method
     if (timedOut && OnError.GetInvocationList().Length > 0)
     {
         OnError(this, new Exception("HARTBEAT: Timed Out."));
     }
     else
     {
         if (_RESPONSE.Text.StartsWith("GOOD") && _RESPONSE.Text.EndsWith("GOOD"))
         {
             _utcOffset = Convert.ToInt32(_RESPONSE.Text.Substring(4, 8), 16);
             log.Info("Ready to capture data.");
         }
         else if (_RESPONSE.Text.StartsWith("FAIL"))
         {
             if (OnError.GetInvocationList().Length > 0)
             {
                 OnError(this, new Exception("HARTBEAT: " + _RESPONSE.Text));
             }
         }
     }
 }
Exemple #5
0
        private void ConnectCallback(IAsyncResult ar)
        {
            // Retrieve the state object and socket from the state object.
            StateObject state = (StateObject)ar.AsyncState;

            try
            {
                // Complete the connection.
                state.WorkSocket.EndConnect(ar);

                // Wait for data to arrive.
                Receive(_bufferSize);
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }

            // Signal that the connection attempt is complete.
            _connectDone.Set();

            // Bubble the event
            if (OnConnected.GetInvocationList().Length > 0)
            {
                OnConnected(this, _socket.Connected);
            }
        }
Exemple #6
0
        private void CallbackCHECKDATA(object state, bool timedOut)
        {
            log.DebugFormat("CHECKDATA [Expected={0}, Received={1}]", _POLLDATA.BytesExpected, _POLLDATA.BytesReceived);
            if (_POLLDATA.BytesExpected > 0 && _POLLDATA.BytesExpected == _POLLDATA.BytesReceived)
            {
                _eventTRACEDONE.Set();
            }
            else if (_POLLDATA.BytesExpected < _POLLDATA.BytesReceived)
            {
                if (_POLLDATA.HandleWAIT != null)
                {
                    _POLLDATA.HandleWAIT.Unregister(null); _POLLDATA.HandleWAIT = null;
                }                                                                                                        // Stop future execution of the callback method
                if (_POLLDATA.HandleDONE != null)
                {
                    _POLLDATA.HandleDONE.Unregister(null); _POLLDATA.HandleDONE = null;
                }                                                                                                        // Stop future execution of the callback method
                _POLLDATA.ClearQs();

                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, new Exception(string.Format(
                                                    "Data Overflow [Expected={0}, Received={1}]", _POLLDATA.BytesExpected, _POLLDATA.BytesReceived)));
                }
            }
            //check for more data every... msRecheckData
        }
Exemple #7
0
 private void CallbackOPENDATA(object state, bool timedOut)
 {
     if (_RESPONSE.Handle != null)
     {
         _RESPONSE.Handle.Unregister(null); _RESPONSE.Handle = null;
     }                                                                                            // Stop future execution of the callback method
     if (timedOut && OnError.GetInvocationList().Length > 0)
     {
         OnError(this, new Exception("OPENDATA: Timed Out."));
     }
     else
     {
         if (_RESPONSE.Text.StartsWith("GOOD") && _RESPONSE.Text.EndsWith("GOOD"))
         {
             // Try to connect to the data port
             int dataport = Convert.ToInt32(_RESPONSE.Text.Substring(4, 8), 16);
             var endpoint = SVSEUtility.CreateIPEndpoint(_socketComm.RemoteIPAddress.ToString(), dataport);
             _socketData.Connect(endpoint);
         }
         else if (_RESPONSE.Text.StartsWith("FAIL"))
         {
             if (OnError.GetInvocationList().Length > 0)
             {
                 OnError(this, new Exception("OPENDATA: " + _RESPONSE.Text));
             }
         }
     }
 }
Exemple #8
0
 void socketData_OnDisconnected(object sender, bool connected)
 {
     if (connected && OnError.GetInvocationList().Length > 0)
     {
         OnError(this, new Exception("Failed to disconnect on command port."));
     }
 }
Exemple #9
0
 void socketData_OnError(object sender, Exception exc)
 {
     // Bubble the event
     if (OnError.GetInvocationList().Length > 0)
     {
         OnError(sender, exc);
     }
 }
Exemple #10
0
 void socketComm_OnError(object sender, Exception exc)
 {
     // throw event
     if (OnError.GetInvocationList().Length > 0)
     {
         OnError(sender, exc);
     }
 }
Exemple #11
0
        public void Startup(string host, int port, string userId, string password)
        {
            _userId   = userId.Trim();
            _password = password.Trim();

            try
            {
                var endpoint = SVSEUtility.CreateIPEndpoint(host.Trim(), port, out _ipAddress);
                _socketComm.Connect(endpoint);
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Invokes the error event.
        /// </summary>
        /// <param name="exception">Exception.</param>
        internal void InvokeOnError(Exception exception)
        {
            if (OnError == null || exception == null)
            {
                return;
            }

            try
            {
                var members = OnError.GetInvocationList().Cast <Func <Exception, Task> >();

                Task.WhenAll(members.Select(x => x(exception)));
                //.Wait(0);
            }
            catch (Exception ex) when(ex.InnerException is TaskCanceledException)
            {
            }
        }
        /// <summary>
        /// Starts monitoring table's content changes.
        /// </summary>
        /// <param name="timeOut">The WAITFOR timeout in seconds.</param>
        /// <param name="watchDogTimeOut">The WATCHDOG timeout in seconds.</param>
        /// <returns></returns>
        public override void Start(int timeOut = 120, int watchDogTimeOut = 180)
        {
            if (timeOut < 60)
            {
                throw new ArgumentException("timeOut must be greater or equal to 60 seconds");
            }
            if (watchDogTimeOut < 60 || watchDogTimeOut < (timeOut + 60))
            {
                throw new WatchDogTimeOutException("watchDogTimeOut must be at least 60 seconds bigger then timeOut");
            }
            if (_task != null)
            {
                return;
            }

            if (OnChanged == null)
            {
                throw new NoSubscriberException();
            }

            var onChangedSubscribedList       = OnChanged?.GetInvocationList();
            var onErrorSubscribedList         = OnError?.GetInvocationList();
            var onStatusChangedSubscribedList = OnStatusChanged?.GetInvocationList();

            NotifyListenersAboutStatus(onStatusChangedSubscribedList, TableDependencyStatus.Starting);

            _disposed = false;

            CreateOrReuseConversation(timeOut, watchDogTimeOut);

            _cancellationTokenSource = new CancellationTokenSource();

            _task = Task.Factory.StartNew(() =>
                                          WaitForNotifications(
                                              _cancellationTokenSource.Token,
                                              onChangedSubscribedList,
                                              onErrorSubscribedList,
                                              onStatusChangedSubscribedList,
                                              timeOut,
                                              watchDogTimeOut),
                                          _cancellationTokenSource.Token);

            WriteTraceMessage(TraceLevel.Info, "Waiting for receiving " + _tableName + "'s records change notifications.", (Exception)null);
        }
Exemple #14
0
        private void CallbackLOGIN(object state, bool timedOut)
        {
            if (_RESPONSE.Handle != null)
            {
                _RESPONSE.Handle.Unregister(null); _RESPONSE.Handle = null;
            }                                                                                            // Stop future execution of the callback method
            if (timedOut && OnError.GetInvocationList().Length > 0)
            {
                OnError(this, new Exception("LOGIN: Timed Out."));
            }
            else
            {
                if (_RESPONSE.Text.StartsWith("GOOD") && _RESPONSE.Text.EndsWith("GOOD"))
                {
                    //open the data port
                    SendPollCommand(SVSECommands.OPENDATA);
                }
                else
                {
                    string loginMess = "Login failed! ";
                    switch (_RESPONSE.Text.Substring(4, 8))
                    {
                    case "LGINSAIN":
                        loginMess += "User already logged in.";
                        break;

                    case "LGINALGI":
                        loginMess += "User already logged in.";
                        break;

                    default:
                        loginMess += _RESPONSE.Text.Substring(4, 8);
                        break;
                    }
                    if (OnError.GetInvocationList().Length > 0)
                    {
                        OnError(this, new Exception(loginMess));
                    }
                }
            }
        }
Exemple #15
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the client socket from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;

            try
            {
                // Read data from the remote device.
                int bytesRead = state.WorkSocket.EndReceive(ar);
                if (bytesRead == 0)
                {
                    // Socket Shutdown is complete, so lets disconnect
                    _socket.BeginDisconnect(true,
                                            new AsyncCallback(DisconnectCallback), _socket);
                    _disconnectDone.WaitOne();
                    return;
                }

                if (EOL != null)
                {
                    string rcvd = Encoding.ASCII.GetString(state.DataRcvd, 0, bytesRead);
                    if (state.TextRcvd == null)
                    {
                        state.TextRcvd = new StringBuilder();//...this must be the first receive
                    }
                    state.TextRcvd.Append(rcvd);

                    if (rcvd.EndsWith(EOL))
                    {
                        // Signal that all bytes have been received.
                        _receiveDone.Set();
                    }

                    // Bubble the event
                    if (OnDataIn.GetInvocationList().Length > 0)
                    {
                        OnDataIn(this, state.DataRcvd);
                    }
                }
                else
                {
                    // Get the actual data received, and put it into a dynamically sized buffer
                    byte[] buffer = new byte[bytesRead];
                    Buffer.BlockCopy(state.DataRcvd, 0, buffer, 0, bytesRead);

                    // Clear the buffer
                    state.DataRcvd = new byte[state.BufferSize];

                    // Bubble the event
                    OnDataIn(this, buffer);
                }

                // Wait for more data
                Receive(_bufferSize);
            }
            catch (Exception exc)
            {
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, exc);
                }
            }
        }
Exemple #16
0
        public static void ClearListeners()
        {
            try
            {
                if (OnDebug != null)
                {
                    foreach (Delegate invoker in OnDebug.GetInvocationList())
                    {
                        OnDebug -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                if (OnError != null)
                {
                    foreach (Delegate invoker in OnError.GetInvocationList())
                    {
                        OnError -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                if (OnFatal != null)
                {
                    foreach (Delegate invoker in OnFatal.GetInvocationList())
                    {
                        OnFatal -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                if (OnInfo != null)
                {
                    foreach (Delegate invoker in OnInfo.GetInvocationList())
                    {
                        OnInfo -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                if (OnVerbose != null)
                {
                    foreach (Delegate invoker in OnVerbose.GetInvocationList())
                    {
                        OnVerbose -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                if (OnWarn != null)
                {
                    foreach (Delegate invoker in OnWarn.GetInvocationList())
                    {
                        OnWarn -= (LogEventHandler)invoker;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemple #17
0
        /// <summary>
        /// Send the next poll command and register wait handles
        /// </summary>
        /// <param name="COMMAND"></param>
        private void SendPollCommand(SVSECommands COMMAND)
        {
            _currCommand = COMMAND;
            string CmdTxt = "";

            switch (COMMAND)
            {
            case SVSECommands.LOGIN:
                CmdTxt           = String.Format("LOGIN {0} {1}", _userId, _password) + "\n";
                _RESPONSE.Handle = ThreadPool.RegisterWaitForSingleObject(
                    _eventRESPONSE,                                 //Register Wait Handle
                    new WaitOrTimerCallback(CallbackLOGIN),         //Delegate/method to call when signaled
                    COMMAND,                                        //Object passed to the delegate
                    msResponseTimeout,                              //Timeout
                    true);
                break;

            case SVSECommands.OPENDATA:
                string verStr = "010500";
                CmdTxt           = "OPENDATA " + verStr + "\n";
                _RESPONSE.Handle = ThreadPool.RegisterWaitForSingleObject(
                    _eventRESPONSE,                                 //Register Wait Handle
                    new WaitOrTimerCallback(CallbackOPENDATA),      //Delegate/method to call when signaled
                    COMMAND,                                        //Object passed to the delegate
                    msResponseTimeout,                              //Timeout
                    true);
                break;

            case SVSECommands.HARTBEAT:
                CmdTxt           = COMMAND.ToString() + "\n";
                _RESPONSE.Handle = ThreadPool.RegisterWaitForSingleObject(
                    _eventRESPONSE,                                 //Register Wait Handle
                    new WaitOrTimerCallback(CallbackHARTBEAT),      //Delegate/method to call when signaled
                    COMMAND,                                        //Object passed to the delegate
                    msResponseTimeout,                              //Timeout
                    true);
                break;

            case SVSECommands.TRACIP01:
                CmdTxt = "GETDATA " + COMMAND.ToString() + "\n";
                _POLLDATA.HandleDONE = ThreadPool.RegisterWaitForSingleObject(
                    _eventTRACEDONE,                               //Register Wait Handle
                    new WaitOrTimerCallback(CallbackTRACEDONE),    //Delegate/method to call when signaled
                    COMMAND,                                       //Object passed to the delegate
                    msTraceTimeout,                                //Timeout
                    true);
                break;

            default:
                //This should never happen...
                CmdTxt = "GETDATA " + COMMAND.ToString() + "\n";
                break;
            }

            if (_socketComm.Connected)
            {
                _socketComm.Send(CmdTxt, 17);
            }
            else if (OnError.GetInvocationList().Length > 0)
            {
                OnError(this, new Exception(string.Format(
                                                "Couldn't send command (connection unavailable): {0}", COMMAND)));
            }
        }
Exemple #18
0
        void socketComm_OnDataIn(object sender, byte[] data)
        {
            string text = Encoding.ASCII.GetString(data);

            _RESPONSE.Text = text.Substring(0, 16);//remove the CRLF
            log.InfoFormat("Rcvd: {0}", _RESPONSE.Text);

            if (_RESPONSE.Handle != null)     //LOGIN, OPENDATA, HARTBEAT
            {
                _eventRESPONSE.Set();         //Execute the waiting method
            }
            else if (text.StartsWith("FAIL")) //Capture Failed
            {
                if (_POLLDATA.HandleWAIT != null)
                {
                    _POLLDATA.HandleWAIT.Unregister(null); _POLLDATA.HandleWAIT = null;
                }                                                                                                        // Stop future execution of the callback method
                if (_POLLDATA.HandleDONE != null)
                {
                    _POLLDATA.HandleDONE.Unregister(null); _POLLDATA.HandleDONE = null;
                }                                                                                                        // Stop future execution of the callback method

                _POLLDATA.ClearQs();
                string description = "Capture failed! ";
                switch (text)
                {
                case "FAILTRACTDNZFAIL": description += "The buffer is not full.";
                    break;

                default: description += text;
                    break;
                }
                if (OnError.GetInvocationList().Length > 0)
                {
                    OnError(this, new Exception(description));
                }
            }
            else
            {   //Capture Succeeded
                if (text.Substring(8, 4) == "DONE")
                {
                    // The server has finished sending data but it is possible that we
                    // have not received it all on the data port, so this will cause the
                    // callback method to run periodically until all the data is received
                    _POLLDATA.HandleWAIT = ThreadPool.RegisterWaitForSingleObject(
                        _eventCHECKDATA,                                     //Register Wait Handle
                        new WaitOrTimerCallback(CallbackCHECKDATA),          //Delegate/method to call when signaled
                        null,                                                //Object passed to the delegate
                        msRecheckData,                                       //Timeout
                        false);

                    _eventCHECKDATA.Set();//Check now
                }
                else
                {   //Store the response
                    SVSEResponse response = new SVSEResponse();
                    response.Text   = _currCommand.ToString();
                    response.Count  = Convert.ToInt32(text.Substring(4, 4), 10);
                    response.Length = Convert.ToInt32(text.Substring(8, 4), 10);
                    _POLLDATA.GoodQ.Enqueue(response);
                }
            }
        }