public void SendNextQueuedCommand() { if (!CommandQueue.IsEmpty) { cmdTimer.StartTimer(60); CommandQueueInProgress = true; if (CommandQueue.Peek() is EtcCommand) { EtcCommand nextCommand = (EtcCommand)CommandQueue.Dequeue(); SendCommand(nextCommand); } else { string nextCommand = (string)CommandQueue.Dequeue(); SendLine(nextCommand); } } else { CommandQueueInProgress = false; cmdTimer.StopTimer(); } }
private void RxWaitCallback(object o) { if (TxQueue.Count == 0) { LastCommand = eCommands.Idle; CrestronConsole.PrintLine("rx timeout, nothing in queue"); } else { LastCommand = TxQueue.Dequeue(); CrestronConsole.PrintLine("rx timeout, sending {0}", LastCommand.ToString()); //if (LastCommand == eCommands.VolumeChange) //{ // _com.Send(GetVolumeString()); // RxWaitTimer.Reset(500); //} //else //{ _com.Send(CommandStrings[LastCommand]); RxWaitTimer.Reset(500); //} } CrestronConsole.PrintLine("There are {0} commands in queue", TxQueue.Count); }
private static object FileWriteProcess(object userSpecific) { Notice("CloudLog FileWriteProcess Started"); while (true) { CrestronEnvironment.AllowOtherAppsToRun(); var log = FileWriteQueue.Dequeue(); using (var writer = CurrentLogFile.AppendText()) { writer.WriteLine(log); while (!FileWriteQueue.IsEmpty) { writer.WriteLine(FileWriteQueue.Dequeue()); } } if (_programEnding && FileWriteQueue.IsEmpty) { return(null); } } }
void HandleQueue(object o) { while (true) { try { var data = _queue.Dequeue(); if (data == null) { return; } if (Debug) { CrestronConsole.PrintLine("Sennheiser - {0} - Sending data: {1}", _client.AddressToAcceptConnectionFrom, data); } if (_connected) { var bytes = _encoding.GetBytes(data); _client.SendData(bytes, bytes.Length); CrestronEnvironment.Sleep(25); } } catch (Exception ex) { ErrorLog.Error("Sennheiser - Exception in UdpTransport.HandleQueue: " + ex.Message); } } }
private static void WriteQueueToDisk(object _) { if (Enable) { try { if (!_writeLock.TryEnter()) { return; } if (!_queue.IsEmpty) { var sb = new StringBuilder(8192); while (!_queue.IsEmpty) { string logItem; if (_queue.Dequeue(out logItem)) { sb.Append(logItem); } } using (var sw = new StreamWriter(string.Format("\\User\\Logs\\{0} {1:yyyy-MM-dd}.log", _asmName.Name, DateTime.Now), true)) sw.Write(sb.ToString()); } } finally { _writeLock.Leave(); } } }
public void Send(string str) { var bytes = new byte[str.Length + 1]; for (int i = 0; i < str.Length; i++) { bytes[i] = unchecked ((byte)str[i]); } bytes[str.Length] = 0x0a; _txQueue.Enqueue(bytes); if (_txThread == null || _txThread.ThreadState != Thread.eThreadStates.ThreadRunning) { _txThread = new Thread(specific => { Thread.CurrentThread.Name = string.Format("{0} Tx Handler", GetType().Name); while (_programRunning) { var qBytes = _txQueue.Dequeue(); if (qBytes != null) { #if DEBUG CrestronConsole.Print("QSys Tx: "); Tools.PrintBytes(qBytes, qBytes.Length, true); #endif ComPort.Send(qBytes, qBytes.Length); } } return(null); }, null); } }
object SendThreadProcess(object o) { #if DEBUG CrestronConsole.PrintLine("{0}.SendThreadProcess() Start", this.GetType().Name); #endif while (!_sendQueue.IsEmpty) { byte[] data = _sendQueue.Dequeue(); SocketErrorCodes err = SendPacket(_client, data); #if DEBUG CrestronConsole.PrintLine("{0} Send process result - {1}", this.GetType().Name, err); #endif if (err != SocketErrorCodes.SOCKET_OK) { ErrorLog.Error("{0}.Send process - Error sending data to socket, {1}", this.GetType().Name, err); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } #if DEBUG CrestronConsole.PrintLine("{0}.SendThreadProcess() End", this.GetType().Name); #endif return(null); }
public void Send(int id, MessageType messageType, byte[] bytes) { var message = new byte[bytes.Length + 5]; message[0] = 0x07; message[1] = (byte)id; message[2] = (byte)messageType; Array.Copy(bytes, 0, message, 3, bytes.Length); message[bytes.Length + 3] = 0x08; message[bytes.Length + 4] = 0x0d; #if DEBUG //CrestronConsole.Print("VT Board Tx: "); //Tools.PrintBytes(message, 0, message.Length, true); #endif _txQueue.Enqueue(message); if (_txThread == null || _txThread.ThreadState != Thread.eThreadStates.ThreadRunning) { _txThread = new Thread(specific => { while (!_txQueue.IsEmpty) { var m = _txQueue.Dequeue(); Send(m, 0, m.Length); Thread.Sleep(200); } return(null); }, null) { Name = string.Format("AvocorSocket Tx Handler"), Priority = Thread.eThreadPriority.MediumPriority }; } }
/// <summary> /// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently. /// It will dequeue items as they are enqueued automatically. /// </summary> void DequeueEvent() { try { while (true) { // Pull from Queue and fire an event. Block indefinitely until an item can be removed, similar to a Gather. var message = MessageQueue.Dequeue(); var dataRecivedExtra = DataRecievedExtra; if (dataRecivedExtra != null) { dataRecivedExtra(this, message); } } } catch (Exception e) { Debug.Console(0, "GenericUdpServer DequeueEvent error: {0}\r", e); } // Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it. if (DequeueLock != null) { DequeueLock.Leave(); } }
object ReceiveBufferProcess(object obj) { var bytes = new Byte[1000]; var byteIndex = 0; while (true) { try { var b = _rxQueue.Dequeue(); if (_programStopping) { return(null); } if (b == 'x') { var copiedBytes = new byte[byteIndex]; Array.Copy(bytes, copiedBytes, byteIndex); #if DEBUG //CrestronConsole.Print("LG Rx: "); //Tools.PrintBytes(copiedBytes, 0, copiedBytes.Length, true); #endif if (ReceivedData != null) { try { ReceivedData(copiedBytes); } catch (Exception e) { CloudLog.Exception(e); } } byteIndex = 0; } else { bytes[byteIndex] = b; byteIndex++; } } catch (Exception e) { if (e.Message != "ThreadAbortException") { #if DEBUG //CrestronConsole.Print("Error in Lg Rx Handler: "); //Tools.PrintBytes(bytes, 0, byteIndex); #endif CloudLog.Exception(string.Format("{0} - Exception in rx thread", GetType().Name), e); } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } }
/// <summary> /// This method gets spooled up in its own thread an protected by a CCriticalSection to prevent multiple threads from running concurrently. /// It will dequeue items as they are enqueued automatically. /// </summary> void DequeueEvent() { try { while (true) { // Pull from Queue and fire an event. Block indefinitely until an item can be removed, similar to a Gather. var message = MessageQueue.Dequeue(); var handler = TextReceivedQueueInvoke; if (handler != null) { handler(this, message); } } } catch (Exception e) { Debug.Console(0, "DequeueEvent error: {0}\r", e); } // Make sure to leave the CCritical section in case an exception above stops this thread, or we won't be able to restart it. if (DequeueLock != null) { DequeueLock.Leave(); } }
private void ResponseQueueDequeue(object o) { if (!responseQueue.IsEmpty) { try { // removes string from queue, blocks until an item is queued string tmpString = responseQueue.Dequeue(); RxData.Append(tmpString); //Append received data to the COM buffer if (!busy) { busy = true; while (RxData.ToString().Contains("\x0D\x0A")) { Pos = RxData.ToString().IndexOf("\x0D\x0A"); var data = RxData.ToString().Substring(0, Pos); var garbage = RxData.Remove(0, Pos + 2); // remove data from COM buffer CrestronConsole.PrintLine("send to parse " + data); ParseInternalResponse(data); } busy = false; } } catch (Exception e) { busy = false; ErrorLog.Exception(e.Message, e); } } }
private object SendBufferProcess(object o) { while (true) { try { var bytes = _txQueue.Dequeue(); if (bytes == null) { CloudLog.Notice("Exiting {0}", Thread.CurrentThread.Name); return(null); } #if DEBUG Debug.WriteInfo("Samsung Tx", Debug.AnsiPurple + Tools.GetBytesAsReadableString(bytes, 0, bytes.Length, false) + Debug.AnsiReset); #endif _comPort.Send(bytes, bytes.Length); CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(10); } catch (Exception e) { if (e.Message != "ThreadAbortException") { CloudLog.Exception(string.Format("{0} - Exception in tx buffer thread", GetType().Name), e); } } } }
object Gather(object o) //second part of the ComPort for the receive for the thread. { StringBuilder rxData = new StringBuilder(); int Pos = -1; String rxGathered = String.Empty; while (true) { try { String rxTemp = rxQueue.Dequeue(); if (rxTemp == null) // Exit the Loop and close the thread when we are done. Set enqueue to null in the stopping program section. { return(null); } rxData.Append(rxTemp); rxGathered = rxData.ToString(); Pos = rxGathered.IndexOf("\n"); if (Pos >= 0) //Zero base string so start at 0 //Hardware is 1 based. { rxGathered = rxGathered.Substring(0, Pos + 1); CrestronConsole.PrintLine("Gather: {0}", rxGathered); rxData.Remove(0, Pos + 1); } } catch (Exception e) { ErrorLog.Error("Exception in Gathering String: {0}", e.Message); } } }
/// <summary> /// Retrieves an object from the pool. /// </summary> /// <returns>Pool object.</returns> public T GetFromPool() { if (_currentCount == 0) { _queueAddEvent.Wait(); } if (_disposed) { return(null); } Interlocked.Decrement(ref _currentCount); var obj = _objectPool.Dequeue(); _queueReturnEvent.Set(); return(obj); }
internal void QueueRequest(ServerRequest request) { RequestQueue.Enqueue(request); if (_dispatchThread != null && _dispatchThread.ThreadState == Thread.eThreadStates.ThreadRunning) { return; } _dispatchThread = new Thread(specific => { #if true Debug.WriteSuccess("AvediaServer", "Launching {0}.DispacthThread, Request Count = {1}", GetType().Name, RequestQueue.Count); Debug.WriteInfo("AvediaServer", "HttpClient Timeout = {0}, TimeoutEnabled = {1}", HttpClient.Timeout, HttpClient.TimeoutEnabled); #endif while (true) { var r = RequestQueue.Dequeue(); if (request == null) { CloudLog.Info("Exiting {0}", Thread.CurrentThread.Name); return(null); } #if true CrestronConsole.PrintLine("{0} {1}", r.RequestType.ToString(), r.Url); if (r.RequestType == RequestType.Post) { CrestronConsole.PrintLine(r.ContentString); } #endif try { var response = HttpClient.Dispatch(r); try { r.Callback(response, HTTP_CALLBACK_ERROR.COMPLETED); } catch (Exception e) { CloudLog.Exception(e); } } catch { r.Callback(null, HTTP_CALLBACK_ERROR.UNKNOWN_ERROR); } CrestronEnvironment.AllowOtherAppsToRun(); } }, null) { Name = "Avedia HTTP dispatch process" }; }
private object ProcessRxData(object obj) { //CrestronConsole.PrintLine("RxHandler thread {ID# {0}) is running", Thread.CurrentThread.ManagedThreadId); StringBuilder RxData = new StringBuilder(); int Pos = -1; String MatchString = String.Empty; // the Dequeue method will wait, making this an acceptable // while (true) implementation. while (true) { try { //CrestronConsole.PrintLine("Crestron proocessing sting data"); // removes string from queue, blocks until an item is queued string tmpString = RxQueue.Dequeue(); if (tmpString == null) { return(null); // terminate the thread } RxData.Append(tmpString); //Append received data to the COM buffer MatchString = RxData.ToString(); //CrestronConsole.PrintLine("matchstring is {0}", MatchString); //find the delimiter Pos = MatchString.IndexOf(Convert.ToChar("\x03")); //Pos = MatchString.IndexOf(Convert.ToChar(etx)); if (Pos >= 0) { // delimiter found // create temporary string with matched data. //CrestronConsole.PrintLine("we achieved delimeter {0}, length {1}",MatchString,MatchString.Length); MatchString = MatchString.Substring(0, Pos); RxData.Remove(0, Pos + 1); // remove data from COM buffer // parse data here //CrestronConsole.PrintLine("Matchstrng is {0}", MatchString); ProcessResponse(MatchString); } } catch (Exception ex) { CrestronConsole.PrintLine("Exception in thread: {0}\n\r{1}", ex.Message, ex.StackTrace); } if (TxQueue.IsEmpty) { LastCommand = eCommands.Idle; //CrestronConsole.PrintLine("Last Command is second {0}, postion is {1}", LastCommand, Pos); } else { LastCommand = TxQueue.Dequeue(); _com.Send(CommandStrings[LastCommand]); RxWaitTimer.Reset(500); } } }
//Comms -------------------------------------------------------------- private void CommandQueueDequeue(object o) { if (!commandQueue.IsEmpty) { var data = commandQueue.Dequeue(); data = generateChecksumString(data); SendDebug(string.Format("Elk - Sending from queue: {0}", data)); client.SendCommand(data + "\x0D\x0A"); } }
/// <summary> /// Sends the next queued command to the DSP /// </summary> private void sendNextQueuedCommand() { if (Communication.IsConnected && !_commandQueue.IsEmpty) { if (_commandQueue.Peek() is QueuedCommand) { _commandInProgress = (QueuedCommand)_commandQueue.Dequeue(); Debug.Console(1, this, "Command '{0}' Dequeued. CommandQueue Size: {1}", _commandInProgress.Command, _commandQueue.Count); _commandInProgressTimer.Reset(2000); sendLine(_commandInProgress.Command); } else { string nextCommand = (string)_commandQueue.Dequeue(); Debug.Console(1, this, "Command '{0}' Dequeued. CommandQueue Size: {1}", nextCommand, _commandQueue.Count); sendLine(nextCommand); } } }
/// <summary> /// Sends the next queued command to the device /// </summary> private void sendNextQueuedCommand() { if (_sendQueue.Count > 0) { _sendQueueCommandInProgress = _sendQueue.Dequeue(); logMessage(1, "Command '{0}' Dequeued. CommandQueue Size: {1}", _sendQueueCommandInProgress.ToString(), _sendQueue.Count); // start the timer to expire current command in case of no response #if SSHARP _sendQueueItemInProgressTimer.Reset(_commandTimeOut); #else _sendQueueItemInProgressTimer.Change(_commandTimeOut, Timeout.Infinite); #endif _sendData(_sendQueueCommandInProgress); } }
private object SendProcess(object userSpecific) { while (_sendQueue.Count > 0) { var message = _sendQueue.Dequeue(); #if DEBUG CrestronConsole.PrintLine(Debug.AnsiGreen + "Yamaha Tx: {0}" + Debug.AnsiReset, message); #endif base.Send(message + "\x0d"); CrestronEnvironment.AllowOtherAppsToRun(); } return(null); }
private object RxThread(object userSpecific) { Byte[] bytes = new Byte[1000]; int byteIndex = 0; while (!_programStopping) { CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); try { byte b = _rxQueue.Dequeue(); if (byteIndex == 7 && b == 0x08) { bytes[byteIndex] = b; var copiedBytes = new Byte[byteIndex + 1]; Array.Copy(bytes, copiedBytes, byteIndex + 1); byteIndex = 0; #if DEBUG CrestronConsole.PrintLine("VT Board Rx: "); Tools.PrintBytes(copiedBytes, copiedBytes.Length, true); #endif OnReceivedData(copiedBytes); } else if (byteIndex == 7 && b != 0x08) { byteIndex = 0; } else { bytes[byteIndex] = b; byteIndex++; } } catch (Exception e) { if (e.Message != "ThreadAbortException") { ErrorLog.Error("{0} - Error in thread: {1}, byteIndex = {2}", GetType().ToString(), e.Message, byteIndex); } } } return(null); }
private void ProcessResponse(object obj) { string rxString = string.Empty; while (true) { try { rxString = cmdQueue.Dequeue(); triggerRxEvent(rxString); } catch (Exception e) { ErrorLog.Error("Error while processing command response: {0} -- {1}", e.Message, e.StackTrace); } } }
private void DataReceivedDequeue(object o) { try { if (!_receivedData.IsEmpty) { ParseDataReceived(_receivedData.Dequeue()); } } catch (Exception e) { if (_debug) { ErrorLog.Exception("Exception occured in WattstopperDLM.Processor.DataReceivedDequeue", e); } } }
/// <summary> /// Handles a response message from the DSP /// </summary> /// <param name="obj"></param> private object parseResponse(object obj) { while (true) { try { string respnose = _responseQueue.Dequeue(); Debug.Console(1, this, "Response '{0}' Dequeued. ResponseQueue Size: {1}", respnose, _responseQueue.Count); if (respnose == null) { Debug.Console(2, this, "Exception in parseResponse thread, deque string is empty"); return(null); } if (respnose.StartsWith("OK> #", StringComparison.Ordinal) || respnose.StartsWith("> #", StringComparison.Ordinal)) { if (_commandInProgress == null) { /// response is not associated with any particular command, iterate through controls parseAll(respnose); } else { _commandInProgressTimer.Stop(); if (!_commandInProgress.Control.Parse(respnose)) { /// current command owner could not parse response, iterating through all others parseAll(respnose); } _commandInProgress = null; } } } catch (Exception e) { Debug.Console(2, this, "Exception in parseResponse thread: '{0}'\n{1}", e.Message, e.StackTrace); } if (!_commandQueue.IsEmpty && _responseQueue.IsEmpty) { sendNextQueuedCommand(); } } // while(true) }
private void ProcessResponses(object o) { String str; while (true) { try { str = myQueue.Dequeue(); //Send Command response to Simpl Sharp Pro myEventToSsp(str); parseData(str); } catch (Exception e) { ErrorLog.Error("Process Response Error: {0}", e.Message); } } }
object RxHandler(object o) { while (true) { try { var bytes = _rxQueue.Dequeue(); if (bytes == null) { CloudLog.Notice("Bytes returned null. Program stopping? Exiting {0}", Thread.CurrentThread.Name); return(null); } for (var i = 0; i < bytes.Length; i++) { switch (bytes[i]) { case 10: break; case 13: OnDataReceived(Encoding.ASCII.GetString(_bytes, 0, _byteIndex)); _byteIndex = 0; break; default: _bytes[_byteIndex] = bytes[i]; _byteIndex++; break; } } } catch (Exception ex) { ErrorLog.Exception("Exception in Codec Rx thread:", ex); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } }
// Callback method for thread object Gather(object o) { StringBuilder rxData = new StringBuilder(); String rxGathered = String.Empty; string rxTemp = ""; // When I had the var definition for string inside the try it blew up int Pos = -1; while (true) { try { rxTemp = rxQueue.Dequeue(); if (rxTemp == null) { return(null); } else { CrestronConsole.PrintLine(rxTemp); } rxData.Append(rxTemp); rxGathered = rxData.ToString(); Pos = rxGathered.IndexOf("\n"); if (Pos >= 0) { rxGathered.Substring(0, Pos + 1); rxData.Remove(0, Pos + 1); } } catch (System.ArgumentOutOfRangeException e) { ErrorLog.Error("Error gathering - ArgumentOutOfRangeException: {0}", e); } catch (Exception e) { ErrorLog.Error("Error gathering: {0}", e); } } }
private void ProcessResponses(object o) { String _str; while (true) { try { _str = myQueue.Dequeue(); //Send command response to SSP myEventToSsp(_str); // Look for IP, DHCP Server, and Lease Experation parseData(_str); } catch (Exception ex) { ErrorLog.Error(String.Format("ProcessResponses Error: {0}", ex.Message)); } } }
object RxMethod(object obj) { StringBuilder RxData = new StringBuilder(); int Pos = -1; String MatchString = String.Empty; // the Dequeue method will wait, making this an acceptable // while (true) implementation. while (true) { try { // removes string from queue, blocks until an item is queued string tmpString = RxQueue.Dequeue(); if (tmpString == null) { return(null); // terminate the thread } RxData.Append(tmpString); //Append received data to the COM buffer MatchString = RxData.ToString(); //find the delimiter Pos = MatchString.IndexOf(Convert.ToChar("\n")); if (Pos >= 0) { // delimiter found // create temporary string with matched data. MatchString = MatchString.Substring(0, Pos + 1); RxData.Remove(0, Pos + 1); // remove data from COM buffer // parse data here } } catch (Exception ex) { ErrorLog.Error("Exception in thread: {0}", ex.Message); } } }