Пример #1
0
 public void Send(string data)
 {
     if (_connected)
     {
         _queue.TryToEnqueue(data);
     }
 }
Пример #2
0
        /// <summary>
        /// Recursive method to receive data
        /// </summary>
        /// <param name="server"></param>
        /// <param name="numBytes"></param>
        void Receive(UDPServer server, int numBytes)
        {
            Debug.Console(2, this, "Received {0} bytes", numBytes);

            if (numBytes > 0)
            {
                var sourceIp   = Server.IPAddressLastMessageReceivedFrom;
                var sourcePort = Server.IPPortLastMessageReceivedFrom;
                var bytes      = server.IncomingDataBuffer.Take(numBytes).ToArray();
                var str        = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
                MessageQueue.TryToEnqueue(new GenericUdpReceiveTextExtraArgs(str, sourceIp, sourcePort, bytes));

                Debug.Console(2, this, "Bytes: {0}", bytes.ToString());
                var bytesHandler = BytesReceived;
                if (bytesHandler != null)
                {
                    bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
                }
                else
                {
                    Debug.Console(2, this, "bytesHandler is null");
                }
                var textHandler = TextReceived;
                if (textHandler != null)
                {
                    if (StreamDebugging.RxStreamDebuggingIsEnabled)
                    {
                        Debug.Console(0, this, "Recevied: '{0}'", str);
                    }

                    textHandler(this, new GenericCommMethodReceiveTextArgs(str));
                }
                else
                {
                    Debug.Console(2, this, "textHandler is null");
                }
            }
            server.ReceiveDataAsync(Receive);

            //  Attempt to enter the CCritical Secion and if we can, start the dequeue thread
            var gotLock = DequeueLock.TryEnter();

            if (gotLock)
            {
                CrestronInvoke.BeginInvoke((o) => DequeueEvent());
            }
        }
Пример #3
0
        public void Send(byte[] bytes)
        {
            // Packet must start with correct header
            if (bytes[0] == 0xAA)
            {
                int dLen   = bytes[3];
                var packet = new byte[dLen + 5];
                Array.Copy(bytes, packet, bytes.Length);
                var chk = 0;
                for (var i = 1; i < bytes.Length; i++)
                {
                    chk = chk + bytes[i];
                }
                packet[packet.Length - 1] = (byte)chk;

                if (!_txQueue.TryToEnqueue(packet))
                {
                    CloudLog.Error("Error in {0}, could not Enqueue packet to send", this.GetType().Name);
                }

                if (_txThread != null && _txThread.ThreadState == Thread.eThreadStates.ThreadRunning)
                {
                    return;
                }
                _txThread = new Thread(SendBufferProcess, null, Thread.eThreadStartOptions.CreateSuspended)
                {
                    Priority = Thread.eThreadPriority.HighPriority,
                    Name     = string.Format("Samsung Display ComPort - Tx Handler")
                };
                _txThread.Start();
            }
            else
            {
                throw new FormatException("Packet did not begin with correct value");
            }
        }
Пример #4
0
        internal static void WriteLog(LoggingLevel level, string message, string process, string stack, bool printToConsole)
        {
            var now = DateTime.UtcNow;

            _idCount++;
            var id   = now.ToString("s") + "_" + _idCount;
            var m    = message;
            var info = string.Empty;

            if (message.Contains(CrestronEnvironment.NewLine))
            {
                var lines = message.Split(CrestronEnvironment.NewLine.ToCharArray());
                m    = lines.First();
                info = String.Join(CrestronEnvironment.NewLine, lines
                                   .Where(l => l.Length > 0)
                                   .Skip(1)
                                   .ToArray());
            }
            var entry = new LogEntry
            {
                Time    = now,
                Id      = id,
                Level   = level,
                Message = m,
                Info    = info,
                Process = process,
                Stack   = stack
            };

            InternalDictionaryLock.Enter();
            InternalDictionary[entry.Id] = entry;
            InternalDictionaryLock.Leave();
            if (CurrentLogFile != null)
            {
                if (!FileWriteQueue.TryToEnqueue(entry))
                {
                    Error("Could not enqueue log entry to file write queue!");
                }
            }

            try
            {
                UploadEvent.Set();
            }
            catch (Exception e)
            {
                ErrorLog.Error("Error setting UploadEvent in WriteLog, {0}", e.Message);
            }

            if (!printToConsole)
            {
                return;
            }
            if (entry.Level >= LoggingLevel.Error)
            {
                Lib2.Debug.WriteError(entry.ToString(true));
            }
            else
            {
                switch (entry.Level)
                {
                case LoggingLevel.Warning:
                    Lib2.Debug.WriteWarn(entry.ToString(true));
                    break;

                case LoggingLevel.Notice:
                    Lib2.Debug.WriteInfo(entry.ToString(true));
                    break;

                case LoggingLevel.Info:
                    Lib2.Debug.WriteSuccess(entry.ToString(true));
                    break;

                default:
                    Lib2.Debug.WriteNormal(entry.ToString(true));
                    break;
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Receive callback
        /// </summary>
        /// <param name="client"></param>
        /// <param name="numBytes"></param>
        void Receive(SecureTCPClient client, int numBytes)
        {
            if (numBytes > 0)
            {
                string str     = string.Empty;
                var    handler = TextReceivedQueueInvoke;
                try
                {
                    var bytes = client.IncomingDataBuffer.Take(numBytes).ToArray();
                    str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
                    Debug.Console(2, this, "Client Received:\r--------\r{0}\r--------", str);
                    if (!string.IsNullOrEmpty(checkHeartbeat(str)))
                    {
                        if (SharedKeyRequired && str == "SharedKey:")
                        {
                            Debug.Console(2, this, "Server asking for shared key, sending");
                            SendText(SharedKey + "\n");
                        }
                        else if (SharedKeyRequired && str == "Shared Key Match")
                        {
                            StopWaitForSharedKeyTimer();


                            Debug.Console(2, this, "Shared key confirmed. Ready for communication");
                            OnClientReadyForcommunications(true); // Successful key exchange
                        }
                        else
                        {
                            //var bytesHandler = BytesReceived;
                            //if (bytesHandler != null)
                            //    bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
                            var textHandler = TextReceived;
                            if (textHandler != null)
                            {
                                textHandler(this, new GenericTcpServerCommMethodReceiveTextArgs(str));
                            }
                            if (handler != null)
                            {
                                MessageQueue.TryToEnqueue(new GenericTcpServerCommMethodReceiveTextArgs(str));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Console(1, this, "Error receiving data: {1}. Error: {0}", ex.Message, str);
                }
                if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    client.ReceiveDataAsync(Receive);
                }

                //Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
                if (handler != null)
                {
                    var gotLock = DequeueLock.TryEnter();
                    if (gotLock)
                    {
                        CrestronInvoke.BeginInvoke((o) => DequeueEvent());
                    }
                }
            }
            else //JAG added this as I believe the error return is 0 bytes like the server. See help when hover on ReceiveAsync
            {
                client.DisconnectFromServer();
            }
        }
        /// <summary>
        /// Secure Received Data Async Callback
        /// </summary>
        /// <param name="mySecureTCPServer"></param>
        /// <param name="clientIndex"></param>
        /// <param name="numberOfBytesReceived"></param>
        void SecureReceivedDataAsyncCallback(SecureTCPServer mySecureTCPServer, uint clientIndex, int numberOfBytesReceived)
        {
            if (numberOfBytesReceived > 0)
            {
                string received = "Nothing";
                var    handler  = TextReceivedQueueInvoke;
                try
                {
                    byte[] bytes = mySecureTCPServer.GetIncomingDataBufferForSpecificClient(clientIndex);
                    received = System.Text.Encoding.GetEncoding(28591).GetString(bytes, 0, numberOfBytesReceived);
                    if (WaitingForSharedKey.Contains(clientIndex))
                    {
                        received = received.Replace("\r", "");
                        received = received.Replace("\n", "");
                        if (received != SharedKey)
                        {
                            byte[] b = Encoding.GetEncoding(28591).GetBytes("Shared key did not match server. Disconnecting");
                            Debug.Console(1, this, Debug.ErrorLogLevel.Warning, "Client at index {0} Shared key did not match the server, disconnecting client. Key: {1}", clientIndex, received);
                            mySecureTCPServer.SendData(clientIndex, b, b.Length);
                            mySecureTCPServer.Disconnect(clientIndex);

                            return;
                        }

                        WaitingForSharedKey.Remove(clientIndex);
                        byte[] success = Encoding.GetEncoding(28591).GetBytes("Shared Key Match");
                        mySecureTCPServer.SendDataAsync(clientIndex, success, success.Length, null);
                        OnServerClientReadyForCommunications(clientIndex);
                        Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Client with index {0} provided the shared key and successfully connected to the server", clientIndex);
                    }
                    else if (!string.IsNullOrEmpty(checkHeartbeat(clientIndex, received)))
                    {
                        onTextReceived(received, clientIndex);
                        if (handler != null)
                        {
                            MessageQueue.TryToEnqueue(new GenericTcpServerCommMethodReceiveTextArgs(received, clientIndex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Receiving data: {0}. Error: {1}", received, ex);
                }
                if (mySecureTCPServer.GetServerSocketStatusForSpecificClient(clientIndex) == SocketStatus.SOCKET_STATUS_CONNECTED)
                {
                    mySecureTCPServer.ReceiveDataAsync(clientIndex, SecureReceivedDataAsyncCallback);
                }

                //Check to see if there is a subscription to the TextReceivedQueueInvoke event. If there is start the dequeue thread.
                if (handler != null)
                {
                    var gotLock = DequeueLock.TryEnter();
                    if (gotLock)
                    {
                        CrestronInvoke.BeginInvoke((o) => DequeueEvent());
                    }
                }
            }
            else
            {
                mySecureTCPServer.Disconnect(clientIndex);
            }
        }