private void AdvanceQueue(string cmd) { if (_commandQueue.IsEmpty) { return; } if (_commandQueue.Peek() is QueuedCommand) { // Expected response belongs to a child class var tempCommand = (QueuedCommand)_commandQueue.TryToDequeue(); Debug.Console(1, this, "Command Dequeued. CommandQueue Size: {0} {1}", _commandQueue.Count, tempCommand.Command); tempCommand.ControlPoint.ParseGetMessage(tempCommand.AttributeCode, cmd); } Debug.Console(2, this, "Commmand queue {0}.", _commandQueue.IsEmpty ? "is empty" : "has entries"); if (_commandQueue.IsEmpty) { _commandQueueInProgress = false; } else { SendNextQueuedCommand(); } }
private void CommandQueueDequeue(object o) { try { if (!commandQueue.IsEmpty) { var data = commandQueue.TryToDequeue(); if (debug == 2) { CrestronConsole.PrintLine("Command sent ** {0} **", data); } if (!externalConnection) { client.SendCommand(data + "\x00"); } else if (onSendingCommand != null) { onSendingCommand(data + "\x00"); } } } catch (Exception e) { if (debug == 1 || debug == 2) { ErrorLog.Error("Error in QsysProcessor CommandQueueDequeue: {0}", e.Message); } } }
private static void CommandQueueDequeue(object o) { try { if (!commandQueue.IsEmpty) { var data = commandQueue.TryToDequeue(); if (debug == 2) { CrestronConsole.PrintLine("Command sent ** {0} **", data); } client.SendCommand(data + "\x00"); } } catch (Exception e) { } }
private static void ResponseQueueDequeue(object o) { try { if (!responseQueue.IsEmpty) { // removes string from queue, blocks until an item is queued string tmpString = responseQueue.TryToDequeue(); RxData.Append(tmpString); //Append received data to the COM buffer if (!busy && RxData.Length > 0 && RxData.ToString().Contains("\x00")) { busy = true; while (RxData.ToString().Contains("\x00")) { Pos = RxData.ToString().IndexOf("\x00"); var data = RxData.ToString().Substring(0, Pos); var garbage = RxData.Remove(0, Pos + 1); // remove data from COM buffer if (debug == 2) { CrestronConsole.PrintLine("Response found ** {0} **", data); } ParseInternalResponse(data); } busy = false; } } } catch (Exception e) { busy = false; if (debug == 1 || debug == 2) { ErrorLog.Error("Error in QsysProcessor ResponseQueueDequeue: {0}", e.Message); } } }
// Methods private void Login(object timer) { if (_Socket.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { _Socket.SocketStatusChange -= SocketStatusHandler; _Socket.DisconnectFromServer(); } SocketErrorCodes err = _Socket.ConnectToServer(); while (_Socket.ClientStatus == SocketStatus.SOCKET_STATUS_WAITING) { Thread.Sleep(100); } if (_Socket.ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED) { ErrorLog.Error("Error connecting to " + this.Name); } _Socket.SocketStatusChange += new TCPClientSocketStatusChangeEventHandler(SocketStatusHandler); string data = ""; int rxlen = 0; // Check for splash screen Thread.Sleep(250); while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } // Check for prompt // Send login if (data.Contains("\r\n> ")) { _SentMessages.TryToDequeue(); SendCmd("login\r\n"); } else // if no prompt, send another line feed { SendCmd("\r\n"); // Check for prompt again Thread.Sleep(250); while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } // On prompt, send login if (data.Contains("\r\n> ")) { _SentMessages.TryToDequeue(); SendCmd("login\r\n"); } } // Check for username prompt: Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("user name:")) // Send the username { _SentMessages.TryToDequeue(); SendCmd("gear7support\r\n"); } // Check for password prompt Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("password:"******"password123!\r\n"); } // Check for success / failure Thread.Sleep(250); data = ""; while (_Socket.DataAvailable) { rxlen = _Socket.ReceiveData(); data += Encoding.ASCII.GetString(_Socket.IncomingDataBuffer, 0, rxlen); } if (data.Contains("login success")) { _SentMessages.TryToDequeue(); ErrorLog.Notice("Logged in to " + this.Name); GetOutlets(); _PollTimer = new CTimer(new CTimerCallbackFunction(Poll), 30000); return; } else { _SentMessages.TryToDequeue(); ErrorLog.Error("Couldn't log in to " + this.Name); _LoginCount++; if (_LoginCount < 5) { _LoginTimer = new CTimer(new CTimerCallbackFunction(Login), 5000); } return; } }
private object SshCommsProcess(object userSpecific) { try { Thread.Sleep(1000); Debug.WriteInfo(string.Format("{0} attempting connection to {1}", GetType().Name, _address)); var firstFail = false; while (!_client.IsConnected && _reconnect) { try { ConnectionStatus = ClientStatus.AttemptingConnection; _client.Connect(); } catch { ConnectionStatus = ClientStatus.Disconnected; if (!firstFail) { CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected", GetType().Name, _address); firstFail = true; } Thread.Sleep(30000); } } if (!_client.IsConnected && !_reconnect) { _client.Dispose(); _client = null; ConnectionStatus = ClientStatus.Disconnected; return(null); } CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address); _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, BufferSize); var buffer = new byte[BufferSize]; var dataCount = 0; try { while (_programRunning && _client.IsConnected) { while (_shell.CanRead && _shell.DataAvailable) { var incomingData = new byte[BufferSize]; var incomingDataCount = _shell.Read(incomingData, 0, incomingData.Length); #if DEBUG _stopWatch.Start(); Debug.WriteSuccess("Tesira rx {0} bytes", incomingDataCount); //Debug.WriteNormal(Debug.AnsiBlue + // Tools.GetBytesAsReadableString(incomingData, 0, incomingDataCount, true) + // Debug.AnsiReset); #endif if (!Connected && Encoding.ASCII.GetString(incomingData, 0, incomingDataCount) .Contains("Welcome to the Tesira Text Protocol Server...")) { _requestsSent.Clear(); _requestsAwaiting.Clear(); _sendQueue.Enqueue("SESSION set verbose true"); ConnectionStatus = ClientStatus.Connected; _keepAliveTimer = new CTimer(specific => { #if DEBUG Debug.WriteInfo(GetType().Name + " Sending KeepAlive"); #endif _client.SendKeepAlive(); }, null, KeepAliveTime, KeepAliveTime); } else if (Connected) { for (var i = 0; i < incomingDataCount; i++) { buffer[dataCount] = incomingData[i]; if (buffer[dataCount] == 10) { //skip } else if (buffer[dataCount] != 13) { dataCount++; } else { if (dataCount == 0) { continue; } var line = Encoding.UTF8.GetString(buffer, 0, dataCount); dataCount = 0; #if DEBUG Debug.WriteSuccess("Tesira Rx Line", Debug.AnsiPurple + line + Debug.AnsiReset); #endif TesiraMessage message = null; if (line == "+OK") { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteSuccess(line); #endif message = new TesiraResponse(request, null); } } else if (line.StartsWith("+OK ")) { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteSuccess(line); #endif message = new TesiraResponse(request, line.Substring(4)); } } else if (line.StartsWith("-ERR ")) { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteError(line); #endif message = new TesiraErrorResponse(request, line.Substring(5)); } else { Debug.WriteError("Error received and request queue returned null!"); Debug.WriteError(line); Debug.WriteError("Clearing all queues!"); _requestsSent.Clear(); _requestsAwaiting.Clear(); } } else if (line.StartsWith("! ")) { #if DEBUG Debug.WriteWarn("Notification Received"); Debug.WriteWarn(line); #endif message = new TesiraNotification(line.Substring(2)); } else if (!_requestsSent.IsEmpty) { Debug.WriteWarn("Last sent request", _requestsSent.Peek()); if (_requestsSent.Peek() == line) { _requestsAwaiting.Enqueue(_requestsSent.Dequeue()); #if DEBUG Debug.WriteNormal("Now awaiting for response for command", line); #endif } } if (message != null && ReceivedData != null && message.Type != TesiraMessageType.ErrorResponse) { if (ReceivedData == null) { continue; } try { _timeOutCount = 0; ReceivedData(this, message); } catch (Exception e) { CloudLog.Exception(e, "Error calling event handler"); } } else if (message != null && message.Type == TesiraMessageType.ErrorResponse) { _timeOutCount = 0; CloudLog.Error("Error message from Tesira: \"{0}\"", message.Message); } } } } #if DEBUG _stopWatch.Stop(); Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds); _stopWatch.Reset(); #endif CrestronEnvironment.AllowOtherAppsToRun(); } if (!_programRunning || !_client.IsConnected) { break; } #if DEBUG //Debug.WriteNormal(Debug.AnsiBlue + // string.Format( // "Shell Can Write = {0}, _sendQueue = {1}, _requestsSent = {2}, _requestsAwaiting = {3}", // _shell.CanWrite, _sendQueue.Count, _requestsSent.Count, // _requestsAwaiting.Count) + Debug.AnsiReset); #endif if (_shell.CanWrite && !_sendQueue.IsEmpty && _requestsSent.IsEmpty && _requestsAwaiting.IsEmpty) { var s = _sendQueue.Dequeue(); if (_keepAliveTimer != null && !_keepAliveTimer.Disposed) { _keepAliveTimer.Reset(KeepAliveTime, KeepAliveTime); } #if DEBUG Debug.WriteWarn("Tesira Tx", s); #endif _timeOutCount = 0; _shell.WriteLine(s); _requestsSent.Enqueue(s); Thread.Sleep(20); } else if (!_requestsSent.IsEmpty || !_requestsAwaiting.IsEmpty) { _timeOutCount++; if (_timeOutCount > 100) { CloudLog.Warn( "Error waiting to send requests in {0}, _requestsAwaiting.Count = {1}" + "and _requestsSent.Count = {2}. Clearing queues!", GetType().Name, _requestsAwaiting.Count, _requestsSent.Count); _requestsAwaiting.Clear(); _requestsSent.Clear(); _timeOutCount = 0; } Thread.Sleep(20); } } } catch (Exception e) { CloudLog.Exception(e); } _loggedIn = false; if (_keepAliveTimer != null && !_keepAliveTimer.Disposed) { _keepAliveTimer.Stop(); _keepAliveTimer.Dispose(); _keepAliveTimer = null; } if (_client != null && _client.IsConnected) { _client.Dispose(); _client = null; } CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address); } catch (Exception e) { CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name); } ConnectionStatus = ClientStatus.Disconnected; if (!_reconnect || !_programRunning) { return(null); } Thread.Sleep(1000); CloudLog.Notice("Attempting reconnect to Tesira at {0}", _address); ConnectionStatus = ClientStatus.AttemptingConnection; Connect(); return(null); }