Пример #1
0
        private void ProcessResponse(CPResponseBase cpResponse, Exception exception)
        {
            if (sendCommand != null)
            {
                sendCommand.SetResult(cpResponse, exception);

                sendCommand = null;
            }
            else
            {// что то пошло не так...
                logger.Warn("!!!!!!!!!!!!!! WARN: " + cpResponse.ToString());
            }
        }
Пример #2
0
        private CPResponseBase SendInternal(CPRequest request, CancellationToken ct, int timeout)
        {
            logger.Debug(request.ToString());

            if (!IsConnected)
            {
                throw new Exception("Not connected");
            }

            if (state != ClientState.Connected)
            {
                throw new Exception("Invalid state: " + state);
            }

            CPResponseBase response = null;

            InvokeCommand command = null;

            try
            {
                command = new InvokeCommand(request, (cSeq++));

                StartCommand(command);

                bool cancel = false;
                ct.Register(() =>
                {
                    cancel = true;
                });

                Func <bool> cancelled = () => (state != ClientState.Connected || cancel);

                response = command.WaitResult(timeout, cancelled) as CPResponseBase;
            }
            finally
            {
                if (command != null)
                {
                    command.Dispose();
                    command = null;
                }
            }

            return(response);
        }
Пример #3
0
        public static bool TryParse(string _resp, out CPResponseBase response)
        {
            response = null;
            bool result = false;

            try
            {
                response = Parse(_resp);
                result   = true;
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.Message);
                Debug.WriteLine(ex);
            }

            return(result);
        }
Пример #4
0
        public static CPResponseBase Parse(string _resp)
        {
            if (string.IsNullOrEmpty(_resp))
            {
                throw new ArgumentException("_resp == null");
            }

            if (!_resp.EndsWith("\r\n"))
            {
                throw new FormatException("Invalid response format: " + _resp);
            }


            CPResponseBase response = null;

            if (_resp.StartsWith("="))
            {// ответ на запрос от сервера
                response = new CPResponse(_resp);
            }
            else if (_resp.StartsWith(":"))
            {// события сервера
                response = new CPNotification(_resp);
            }
            else
            {
                if (_resp.StartsWith("OK") || _resp.StartsWith("ER"))
                {// ответ от Galileo Connect
                    response = new GCResponse(_resp);
                }
                else
                {
                    throw new FormatException("Invalid response format: " + _resp);
                }
            }


            return(response);
        }
Пример #5
0
 private void ProcessNotification(CPResponseBase cpResponse)
 {
     NotificationReceived?.Invoke((CPNotification)cpResponse);
 }
Пример #6
0
        private void CommunicationLoop()
        {
            logger.Verb("CommunicationLoop BEGIN");

            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.ReceiveTimeout = 10000;
                socket.SendTimeout    = 10000;

                logger.Verb($"socket.ConnectAsync(...) {Host} {Port}");

                var connectionTask = socket.ConnectAsync(Host, Port);

                Task.WaitAny(new[] { connectionTask }, 10000);

                if (!IsSocketConnected())
                {
                    throw new Exception("Connection error");
                }

                if (state == ClientState.Connecting)
                {
                    state = ClientState.Connected;
                }

                StateChanged?.Invoke();

                while (true)
                {
                    bool socketConnected = IsSocketConnected();
                    if (!(socketConnected && state == ClientState.Connected))
                    {
                        logger.Debug("Connection break " + socketConnected + " " + state);
                        break;
                    }

                    int available = socket.Available;
                    if (available > 0)
                    {
                        IEnumerable <byte[]> dataLines = null;

                        CPSocketHandler socketHanlder = new CPSocketHandler();

                        Exception exception = null;
                        try
                        {
                            bool bufferProcessed = false;
                            do
                            {
                                byte[] recBuffer = new byte[1024];

                                int bytesRec = socket.Receive(recBuffer);

                                if (bytesRec > 0)
                                { //The ControlPoint protocol is text-based. Each command line terminates
                                  //with CR/LF.Tokens are space separated. All identifiers are case-sensitive.

                                    dataLines = socketHanlder.ReadLines(recBuffer, bytesRec);

                                    bufferProcessed = (dataLines != null);
                                }
                                else
                                {// socket closed...
                                    socketConnected = false;
                                    break;
                                }
                            }while (!bufferProcessed);
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            exception = ex;
                        }

                        if (dataLines != null)
                        {
                            foreach (var bytes in dataLines)
                            {
                                var cpResponse   = CPResponseBase.Create(bytes);
                                var responseType = cpResponse?.ResponseType ?? CPResponseType.Unknown;

                                if (responseType == CPResponseType.Response || cpResponse.ResponseType == CPResponseType.Galileo)
                                {
                                    ProcessResponse(cpResponse, exception);
                                }
                                else if (cpResponse.ResponseType == CPResponseType.Notify)
                                {
                                    ProcessNotification(cpResponse);
                                }
                                else
                                {
                                    ProcessResponse(null, exception);
                                }
                            }

                            dataLines = null;
                        }
                    }

                    socketConnected = IsSocketConnected();
                    if (!(socketConnected && state == ClientState.Connected))
                    {
                        logger.Debug("Connection break " + socketConnected + " " + state);
                        break;
                    }

                    {                            // Response must be received before the next Request is sent!
                        if (sendCommand == null) // обнуляется при получении ответа
                        {
                            if (TryGetCommand(out var command))
                            {
                                try
                                {
                                    var seq     = command.seq;
                                    var request = (CPRequest)command.request;

                                    byte[] sendBuffer = request.GetBytes();
                                    int    bytesSent  = socket.Send(sendBuffer);

                                    sendCommand = command;

                                    logger.Debug(">> " + sendCommand.ToString() + "bytesSent: " + bytesSent);
                                }
                                catch (Exception ex)
                                {
                                    logger.Error(ex);

                                    ProcessResponse(null, ex);
                                }
                            }
                        }
                    }

                    syncEvent.WaitOne(10);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                if (socket != null)
                {
                    if (socket.Connected)
                    {
                        socket.Shutdown(SocketShutdown.Both);
                    }

                    socket.Close();
                    socket = null;
                }

                DrainCommands();

                isAuthenticated = false;
                state           = ClientState.Disconnected;
                StateChanged?.Invoke();
            }

            logger.Verb("CommunicationLoop END");
        }