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); } } } }
protected virtual void DspOnHasIntitialized(QsysCore core) { CloudLog.Notice(string.Format("Q-Sys Core: \"{0}\" Has Intitialized!", core.Name)); foreach (var component in core) { foreach (var control in component) { CloudLog.Info("Core Control: {0}", control.ToString()); } } foreach (var itemConfig in ConfigManager.Config.DspFaderComponents.Where(c => !string.IsNullOrEmpty(c.TrafficLightBaseName))) { try { core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".signal"]); core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".good"]); core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".peak"]); } catch { } } core.GetChangeGroup("TrafficLights").PollAuto(0.2); }
public void Start() { if (_started) { throw new InvalidOperationException("Already started"); } _started = true; var v = _ioPort as Versiport; if (v != null) { _normalState = v.DigitalIn; } else { var d = _ioPort as DigitalInput; if (d != null) { _normalState = d.State; } } CloudLog.Notice("Fire interface normal state set initialized at {0}", _normalState ? "Closed" : "Open"); _socket.Start(); }
protected virtual void OnDeviceCommunicatingChange(IDevice device, bool communicating) { var handler = DeviceCommunicatingChange; if (handler == null) { return; } try { if (communicating) { CloudLog.Notice("{0}.DeviceCommunicating = {1}", GetType().Name, true); } else { CloudLog.Warn("{0}.DeviceCommunicating = {1}", GetType().Name, false); } handler(device, communicating); } catch (Exception e) { CloudLog.Exception(e); } }
public void Connect() { if (_client != null && _client.IsConnected) { CloudLog.Warn("{0} already connected", GetType().Name); return; } _reconnect = true; var info = new KeyboardInteractiveConnectionInfo(_address, _port, _username); info.AuthenticationPrompt += OnPasswordPrompt; _client = new SshClient(info); _client.ErrorOccurred += (sender, args) => CloudLog.Exception(args.Exception, "SshClient.ErrorOccurred Event"); _client.HostKeyReceived += (sender, args) => CloudLog.Notice("{0} HostKeyReceived: {1}, can trust = {2}", GetType().Name, args.HostKeyName, args.CanTrust); _sshProcess = new Thread(SshCommsProcess, null, Thread.eThreadStartOptions.CreateSuspended) { Name = "CodecSshClient Comms Handler", Priority = Thread.eThreadPriority.MediumPriority }; _sshProcess.Start(); }
private bool CheckIfNewVersion(Assembly appAssembly) { try { var runningVersion = appAssembly.GetName().Version; CloudLog.Info("Checking version of {0} to see if \"{1}\" is new", appAssembly.GetName().Name, runningVersion); var filePath = string.Format("{0}\\{1}_version.info", AppStoragePath, appAssembly.GetName().Name); if (!File.Exists(filePath)) { using (var newFile = File.OpenWrite(filePath)) { newFile.Write(runningVersion.ToString(), Encoding.UTF8); } CloudLog.Notice("Version file created at \"{0}\", app must be updated or new", filePath); return(true); } bool appIsNewVersion; using (var file = new StreamReader(filePath, Encoding.UTF8)) { var contents = file.ReadToEnd().Trim(); var version = new Version(contents); appIsNewVersion = runningVersion.CompareTo(version) != 0; if (appIsNewVersion) { CloudLog.Warn("APP UPDATED TO {0}", runningVersion.ToString()); } else { CloudLog.Notice("App version remains as {0}", runningVersion.ToString()); } } if (appIsNewVersion) { File.Delete(filePath); using (var newFile = File.OpenWrite(filePath)) { newFile.Write(runningVersion.ToString(), Encoding.UTF8); } CloudLog.Notice("Version file deleted and created at \"{0}\", with new version number", filePath); } return(appIsNewVersion); } catch (Exception e) { CloudLog.Error("Error checking if app is new version, returning true, {0}", e.Message); return(true); } }
public void Stop() { CloudLog.Notice("Stopping {0} instance on TCP port {1}", GetType().Name, _socket.PortNumber); if (_socket != null) { var message = Encoding.ASCII.GetBytes("Closing connections!\r\n"); SendToAll(message, 0, message.Length); _socket.DisconnectAll(); } }
public void Initialize() { if (_timer != null && !_timer.Disposed) { return; } CloudLog.Notice("{0}.Initialize() for address {1}", GetType().Name, _address); _timer = new CTimer(specific => GetStatus(), null, 1000, 60000); }
protected override void PowerOff(PowerOfFEventType eventType) { Source = null; foreach (var display in Displays.Where(display => display.Device != null)) { #if DEBUG CloudLog.Notice("{0} Power Off!", display.Device.Name); #endif display.Device.Power = false; } }
private object ReceiveHandler(object userSpecific) { var clientIndex = (uint)userSpecific; CloudLog.Notice("{0} rx handler on TCP port {1}, is running for client index {2}", GetType().Name, _socket.PortNumber, clientIndex); try { OnClientConnect(clientIndex); } catch (Exception e) { CloudLog.Exception(e); } while (true) { try { var count = _socket.ReceiveData(clientIndex); if (count <= 0) { CloudLog.Debug("{0} - Client Index {1} Received data count of {2}, Disconnected? - Exiting Thread", GetType().Name, clientIndex, count); try { OnClientDisconnect(clientIndex); } catch (Exception e) { CloudLog.Exception(e); } return(null); } OnClientReceive(clientIndex, _socket.GetIncomingDataBufferForSpecificClient(clientIndex), count); } catch (Exception e) { CloudLog.Exception(e, "Error in {0} for client index {1}, closing connection and exiting rx handler thread", Thread.CurrentThread.Name, clientIndex); if (_connections[clientIndex] == SocketStatus.SOCKET_STATUS_CONNECTED) { _socket.Disconnect(clientIndex); return(null); } } } }
private void AmOnIpInformationChange(GenericBase currentDevice, ConnectedIpEventArgs args) { if (!args.Connected) { return; } CloudLog.Notice("{0} has connected on IP {1}", currentDevice, args.DeviceIpAddress); if (currentDevice.ConnectedIpList.Count == 1) { _deviceIpAddress = currentDevice.ConnectedIpList.First().DeviceIpAddress; } }
public void Start(bool normalState) { if (_started) { throw new InvalidOperationException("Already started"); } _started = true; _normalState = normalState; CloudLog.Notice("Fire interface normal state set initialized at {0}", _normalState ? "Closed" : "Open"); _socket.Start(); }
private void DigitalInputOnStateChange(DigitalInput digitalInput, DigitalInputEventArgs args) { CloudLog.Notice("Fire interface port state change: {0}", args.State ? "Closed" : "Open"); if (!_started) { return; } OnStateChanged(this, args.State != _normalState); var message = string.Format("firestate[{0}]\r\n", args.State == _normalState ? "NORMAL" : "ALERT"); var bytes = Encoding.ASCII.GetBytes(message); _socket.SendToAll(bytes, 0, bytes.Length); }
private object CodecPollingProcess(object userSpecific) { while (!_programStopping) { foreach (var valuePair in _codecAddresses) { var roomId = valuePair.Key; var address = valuePair.Value; try { var uri = new UriBuilder("https", address, 443, "status.xml").Uri; Debug.WriteInfo("Polling Codec", "Room {0}: {1}", roomId, uri.ToString()); var request = new HttpsClientRequest { Url = new UrlParser(uri.ToString()) }; var username = ConfigManager.Config.CodecUsername; var password = ConfigManager.Config.CodecPassword; var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)); request.Header.AddHeader(new HttpsHeader("Authorization", "Basic " + auth)); var response = Client.Dispatch(request); var reader = new XmlReader(response.ContentString); var doc = XDocument.Load(reader); var status = doc.Element("Status"); Debug.WriteSuccess("Codec Online", status.Element("UserInterface").Element("ContactInfo").Element("Name").Value); Debug.WriteSuccess("Mute", status.Element("Audio").Element("Microphones").Element("Mute").Value); Debug.WriteSuccess("In Call", status.Elements("Call").Any().ToString()); Debug.WriteSuccess("Uptime", TimeSpan.FromSeconds(int.Parse(status.Element("SystemUnit").Element("Uptime").Value)).ToPrettyFormat()); Debug.WriteSuccess("Standby", "Status = {0}", status.Element("Standby").Element("State").Value != "Standby"); CrestronConsole.PrintLine(""); } catch (Exception e) { CloudLog.Error("Error polling codec at {0}, {1}", address, e.Message); } } Thread.Sleep(30000); CrestronEnvironment.AllowOtherAppsToRun(); } CloudLog.Notice("Leaving thread: {0}", Thread.CurrentThread.Name); return(null); }
protected virtual void OnInitialized() { CloudLog.Notice("Tesira block {0} \"{1}\" OnInitialized()", GetType().Name, Name); var handler = HasInitialized; if (handler == null) { return; } try { handler(this); } catch (Exception e) { CloudLog.Exception(e); } }
public void Start() { if (_started) { CloudLog.Warn("{0} instance on TCP port {1}, already started", GetType().Name, _socket.PortNumber); return; } _started = true; try { CloudLog.Notice("Starting {0} instance on TCP port {1}", GetType().Name, _portNumber); if (_socket == null || _socket.ServerSocketStatus == SocketStatus.SOCKET_STATUS_SOCKET_NOT_EXIST) { CloudLog.Info("Created new socket for {0} on port {1}", GetType().Name, _portNumber); _socket = new TCPServer(IPAddress.Any.ToString(), _portNumber, _bufferSize, EthernetAdapterType.EthernetUnknownAdapter, _numberOfConnections); _socket.SocketSendOrReceiveTimeOutInMs = 60000; _socket.SocketStatusChange += SocketOnSocketStatusChange; if (_waitForConnectThread == null || _waitForConnectThread.ThreadState != Thread.eThreadStates.ThreadRunning) { _waitForConnectThread = new Thread(ListenForConnections, null) { Name = string.Format("{0} Connection Handler", GetType().Name), Priority = Thread.eThreadPriority.MediumPriority }; } CloudLog.Info("{0} on port {1}\r\nStatus: {2}\r\nMax Connections: {3}", GetType().Name, _socket.PortNumber, _socket.State, _socket.MaxNumberOfClientSupported); } else { CloudLog.Warn("TCP Server. Could not start. Current Socket Status:{0}", _socket.ServerSocketStatus); } } catch (Exception e) { CloudLog.Exception(e, "Could not start socket"); } }
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); } }
private void AirMediaOnAirMediaChange(object sender, GenericEventArgs args) { switch (args.EventId) { case Crestron.DeviceSupport.Support.AirMediaInputSlot.AirMediaImageErrorEventId: var error = ((AmX00)_device).AirMedia.DisplayControl.ImageErrorFeedback.UShortValue; if (error == 0) { CloudLog.Notice("AirMedia {0} background set to \"{1}\"", _device.ID.ToString("X2"), ((AmX00)_device).AirMedia.DisplayControl.ImageURLFeedback.StringValue); } else { CloudLog.Error("AirMedia {0} could not set background to \"{1}\", Error {2}", _device.ID.ToString("X2"), ((AmX00)_device).AirMedia.DisplayControl.ImageURL.StringValue, error); } break; } }
object ReceiveBufferProcess(object obj) { var bytes = new Byte[BufferLen]; var byteIndex = 0; while (true) { try { var b = _rxQueue.Dequeue(); if (_programStopping) { CloudLog.Notice("Exiting {0}", Thread.CurrentThread.Name); return(null); } if (b == 0x0d) { OnReceivedString(Encoding.ASCII.GetString(bytes, 0, byteIndex)); byteIndex = 0; } else if (b != 0x0a) { bytes[byteIndex] = b; byteIndex++; } } catch (Exception e) { if (e.Message != "ThreadAbortException") { CloudLog.Exception(string.Format("{0} - Exception in rx thread", GetType().Name), e); } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } }
private void VersiportOnVersiportChange(Versiport port, VersiportEventArgs args) { if (args.Event == eVersiportEvent.DigitalInChange) { CloudLog.Notice("Fire interface port state change: {0}", port.DigitalIn ? "Closed" : "Open"); } else { return; } if (!_started) { return; } OnStateChanged(this, port.DigitalIn != _normalState); var message = string.Format("firestate[{0}]\r\n", port.DigitalIn == _normalState ? "NORMAL" : "ALERT"); var bytes = Encoding.ASCII.GetBytes(message); _socket.SendToAll(bytes, 0, bytes.Length); }
private void FireAlarmListenerOnStatusChanged(FireAlarmListener listener, FireAlarmStatus status) { var mute = status == FireAlarmStatus.Alert; CloudLog.Warn("Fire Alarm Interface changed status to: {0}", status.ToString()); try { PromptUsers(prompt => { }, "FIRE ALARM", "Please listen for announcements", 300, null, new PromptAction { ActionName = "OK", ActionType = PromptActionType.Acknowledge }); } catch (Exception e) { CloudLog.Exception(e); } if (Dsp != null && Dsp.ContainsComponentWithName("fire.mute")) { var muteGainBlock = Dsp["fire.mute"] as IAudioLevelControl; if (muteGainBlock != null && muteGainBlock.SupportsMute) { CloudLog.Notice("Dsp mute {0} set to {1}", muteGainBlock.Name, mute ? "muted" : "unmuted"); muteGainBlock.Muted = mute; return; } } foreach (var room in Rooms.Cast <ARoom>().Where(room => room.ProgramVolume != null)) { CloudLog.Warn("Fire Alarm {0} program volume in Room {1}", mute ? "muted" : "unmuted", room.Name); room.ProgramVolume.Muted = mute; } }
private void InternalClockInitialize() { _clockInitThread = new Thread(specific => { CloudLog.Debug("InternalClockInitialize(), Waiting for seconds to be 0", GetType().Name); while (DateTime.Now.Second != 0) { Thread.Sleep(50); CrestronEnvironment.AllowOtherAppsToRun(); } CloudLog.Notice("InternalClockInitialize(), Seconds should now be zero, time is now {1}, creating CTimer to track time", GetType().Name, DateTime.Now.ToString("T")); _clockTimer = new CTimer(s => OnTimeChange(), null, 60000, 60000); OnTimeChange(); CloudLog.Info("InternalClockInitialize(), OnTimeChange() will be called every time time is 0 seconds", GetType().Name); return(null); }, null, Thread.eThreadStartOptions.CreateSuspended) { Name = "Clock Init Thread", Priority = Thread.eThreadPriority.HighPriority }; _clockInitThread.Start(); }
private object ListenForConnections(object userSpecific) { CloudLog.Notice("Started {0} connection handler", GetType().Name); while (!_programStopping) { CloudLog.Debug("{0} Waiting for connections...", GetType().Name); if (_socket.NumberOfClientsConnected < _socket.MaxNumberOfClientSupported) { var result = _socket.WaitForConnection(); CloudLog.Debug("{0} Connection result: {1}", GetType().Name, result); } else { CloudLog.Debug("{0} No more connections allowed", GetType().Name); Thread.Sleep(10000); } } CloudLog.Notice("Exiting {0}", Thread.CurrentThread.Name); return(null); }
private object UpdateFeedbackProcess(object userSpecific) { CloudLog.Notice("Started " + Thread.CurrentThread.Name); var feedback = true; var itemStates = new Dictionary <RoutingListItem, ItemState>(); while (RequestedVisibleState && !_programStopping && _switcher.Chassis.IsOnline) { if (_selectedInput != null) { _routedOutputsForSelectedInput = new List <DMOutput>(); foreach ( var output in _switcher.Chassis.Outputs.Values.Where( o => o.VideoOutFeedback != null && o.VideoOutFeedback == _selectedInput)) { _routedOutputsForSelectedInput.Add(output); } foreach (var item in _outputList.Cast <RoutingListItem>().TakeWhile(item => item.LinkedObject != null)) { var output = (DMOutput)item.LinkedObject; var alreadyRouted = _routedOutputsForSelectedInput.Contains(output); var willChange = _outputsToChange.Keys.Contains(output); itemStates[item] = new ItemState { Color = RoutingItemListColor.Blue, Feedback = false }; if (alreadyRouted && willChange) { itemStates[item].Color = RoutingItemListColor.Red; itemStates[item].Feedback = feedback; } else if (willChange && _outputsToChange[output] == _selectedInput) { itemStates[item].Color = RoutingItemListColor.Green; itemStates[item].Feedback = feedback; } else if (alreadyRouted) { itemStates[item].Feedback = true; } } } else { foreach (var item in _outputList.Cast <RoutingListItem>().TakeWhile(item => item.LinkedObject != null)) { itemStates[item] = new ItemState { Color = RoutingItemListColor.Blue, Feedback = false }; } } foreach (var itemState in itemStates) { itemState.Key.Feedback = itemState.Value.Feedback; itemState.Key.Color = itemState.Value.Color; } _cancelButton.Enabled = _outputsToChange.Count > 0 || _selectedInput != null; _takeButton.Enabled = _outputsToChange.Count > 0; if (_updateFeedbackEvent.Wait(500)) { feedback = true; } else { feedback = !feedback; } } if (RequestedVisibleState) { Debug.WriteInfo("Showing DM offline prompt on " + UIController.ToString()); ((BaseUIController)UIController).ActionSheetDefault.Show((type, args) => { }, "Switcher Offline", "The DM Switcher is offline", "OK"); } CloudLog.Notice("Exiting " + Thread.CurrentThread.Name); return(null); }
protected object ConnectionThreadProcess(object o) { var memoryStream = new MemoryStream(); var reader = new StreamReader(memoryStream); var receivedAnything = false; while (true) { var connectCount = 0; while (_remainConnected && !Connected) { connectCount++; _client.AddressClientConnectedTo = _currentAddress; Debug.WriteInfo(GetType().Name, "Address to connect to set to {0}", _currentAddress); var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); receivedAnything = false; break; } TryAnotherAddress(); if (connectCount <= 4 || connectCount > 10) { continue; } if (connectCount == 10) { CloudLog.Error("{0} failed to connect to any address, will keep trying in background", GetType().Name); } else { CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _currentAddress); } CrestronEnvironment.AllowOtherAppsToRun(); } _pollTimer = new CTimer(specific => DoNothing(), null, 30000, 30000); _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { Debug.WriteWarn(GetType().Name, "Disconnected!"); _pollTimer.Stop(); _pollTimer.Dispose(); _pollTimer = null; if (_remainConnected) { if (!receivedAnything) { CloudLog.Warn( "{0} connected but didn't receive anything." + "Will wait for 1 minute before reconnection attempt. Upgrade may be in progress.", GetType().Name); Thread.Sleep(60000); } break; } Debug.WriteWarn("Exiting Thread", Thread.CurrentThread.Name); return(null); } receivedAnything = true; #if DEBUG Debug.WriteInfo(GetType().Name, "{0} bytes in buffer", dataCount); #endif for (var i = 0; i < dataCount; i++) { var b = _client.IncomingDataBuffer[i]; if (b != 0) { memoryStream.WriteByte(b); continue; } memoryStream.Position = 0; try { var data = JToken.Parse(reader.ReadToEnd()); memoryStream.SetLength(0); #if DEBUG Debug.WriteInfo(_name + " Rx", Debug.AnsiBlue + data.ToString(Formatting.None) + Debug.AnsiReset); #endif if (data["method"] != null) { OnRequestReceived(this, new QsysRequest(data)); } else if (data["id"] != null) { var id = data["id"].Value <int>(); if (_requests.ContainsKey(id)) { var request = _requests[id]; _requests.Remove(id); OnResponseReceived(this, new QsysResponse(data, request)); } } } catch (Exception e) { CloudLog.Exception("Error occured processing a complete data parcel from Core", e); } } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } }
public void ConnectionStart() { if (_connectionId > 0 || (_connectionThread != null && _connectionThread.ThreadState == Thread.eThreadStates.ThreadRunning)) { return; } _connectionActive = true; _connectionWait.Reset(); CloudLog.Notice("{0} Initialize() called", GetType().Name); _connectionThread = new Thread(specific => { while (_connectionActive && !_programStopping) { var suppressErrors = false; UriBuilder uri; Task <HttpResponseMessage> task; HttpResponseMessage response; Task <string> readTask; string content; JToken json; while (_connectionId == 0) { try { uri = new UriBuilder("http", _ipAddress, 80, string.Format("config")) { Query = "action=connect" }; Debug.WriteInfo("Trying to connect to " + uri.Uri); task = _client.GetAsync(uri.Uri); response = task.Await(); response.EnsureSuccessStatusCode(); readTask = response.Content.ReadAsStringAsync(); content = readTask.Await(); #if DEBUG Debug.WriteInfo("Response content:\r\n" + content); #endif json = JToken.Parse(content); _connectionId = int.Parse(json["connectionid"].Value <string>()); CloudLog.Debug("{0} connected and received conenction id of \"{1}\"", GetType().Name, _connectionId); try { var eventInfo = json["configevents"].First; _currentClip = eventInfo["eParamID_CurrentClip"].Value <string>(); _transportState = (ETransportState)int.Parse(eventInfo["eParamID_TransportState"].Value <string>()); OnTransportModeChanged(this); } catch (Exception e) { Debug.WriteWarn("Could not parse configevents on connect, {0}", e.Message); } } catch (Exception e) { if (!suppressErrors) { suppressErrors = true; CloudLog.Error("Error trying to connect to {0}, {1}", GetType().Name, e.Message); CloudLog.Warn("{0} will try again in 5 seconds", GetType().Name); } _connectionWait.Wait(5000); DeviceCommunicating = false; } } DeviceCommunicating = true; uri = new UriBuilder("http", _ipAddress, 80, string.Format("config")) { Query = "action=get¶mid=eParamID_TransportState" }; Debug.WriteInfo("Trying to connect to " + uri.Uri); task = _client.GetAsync(uri.Uri); response = task.Await(); response.EnsureSuccessStatusCode(); readTask = response.Content.ReadAsStringAsync(); content = readTask.Await(); #if DEBUG Debug.WriteWarn("Response content:\r\n" + content); #endif json = JToken.Parse(content); TransportState = (ETransportState)int.Parse(json["value"].Value <string>()); while (_connectionActive) { var timeStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; uri = new UriBuilder("http", _ipAddress, 80, string.Format("config")) { Query = string.Format("action=wait_for_config_events&connectionid={0}&_={1}", _connectionId, timeStamp) }; Debug.WriteInfo("Trying to connect to " + uri.Uri); task = _client.GetAsync(uri.Uri); response = task.Await(); if (response.StatusCode == HttpStatusCode.Gone) { _connectionId = 0; break; } response.EnsureSuccessStatusCode(); readTask = response.Content.ReadAsStringAsync(); content = readTask.Await(); #if DEBUG Debug.WriteWarn("Response content:\r\n" + content); #endif json = JToken.Parse(content); foreach (var item in json) { var paramId = item["param_id"].Value <string>(); switch (paramId) { case "eParamID_DisplayTimecode": _timeCode = item["str_value"].Value <string>(); break; case "eParamID_CurrentClip": _currentClip = item["str_value"].Value <string>(); break; case "eParamID_TransportState": _transportState = (ETransportState)item["int_value"].Value <int>(); break; } } OnTransportModeChanged(this); CrestronEnvironment.AllowOtherAppsToRun(); _connectionWait.Wait(100); } } _connectionId = 0; return(null); }, null); }
private void SshClientOnReceivedData(CiscoSshClient client, CodecSshClientReceivedDataArgs args) { var matches = Regex.Matches(args.DataAsReceived, @"\*\w ([^\r\n\""\:]+) (\w+)?(?:\(([\w\=]+)\))?:? ?\""?([^\r\n\""]+)?\""?"); if (matches.Count <= 0) { return; } switch (args.DataType) { case ReceivedDataType.Configuration: foreach (Match configMatch in matches) { try { OnConfigurationChanged(this, new ConfigurationChangeEventArgs { Path = configMatch.Groups[1].Value, PropertyName = configMatch.Groups[2].Value, Value = configMatch.Groups[4].Value }); } catch (Exception e) { CloudLog.Exception(e); } } break; case ReceivedDataType.Status: OnStatusReceived((from Match statusMatch in matches select new StatusUpdateItem(statusMatch)) .ToArray()); if (_initialized) { return; } CloudLog.Notice("{0} Initialized OK", this); _initialized = true; break; case ReceivedDataType.Event: var items = new Dictionary <string, Dictionary <string, string> >(); foreach (Match eventMatch in matches) { if (!items.ContainsKey(eventMatch.Groups[1].Value)) { items.Add(eventMatch.Groups[1].Value, new Dictionary <string, string>()); } if (eventMatch.Groups[4].Success) { items[eventMatch.Groups[1].Value][eventMatch.Groups[2].Value] = eventMatch.Groups[4].Value; } else { items[eventMatch.Groups[1].Value][eventMatch.Groups[2].Value] = string.Empty; } } foreach (var item in items) { OnEventReceived(item.Key, item.Value); } break; case ReceivedDataType.Response: foreach (Match response in matches) { #if DEBUG Debug.WriteInfo("Response", "{0} {1} {2}", response.Groups[1].Value, response.Groups[2].Value, response.Groups[3].Value); #endif } break; } }
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); }
protected void StartWebApp(int portNumber) { CloudLog.Notice("Starting web app on port {0}", portNumber); _webApp = new WebApp.WebApp(this, portNumber); OnWebAppStarted(); }
internal bool StartSession() { CodecRequest request; CodecResponse response; CloudLog.Info("Cisco Codec StartSession() called"); if (!string.IsNullOrEmpty(_sessionId)) { try { CloudLog.Debug("Codec has session ID already... attempting to close it"); request = new CodecRequest(_address, "/xmlapi/session/end", _sessionId) { RequestType = RequestType.Post }; response = Dispatch(request); #if DEBUG Debug.WriteInfo("Received headers for session end:\r\n" + response.Header); #endif CloudLog.Debug("Session close request result: {0}", response.Code); } catch (Exception e) { Debug.WriteError("Error trying to close session on codec", "Session ID to close: {0}, Error: {1}\r\nStackTrace: {2}", _sessionId, e.Message, e.StackTrace); CloudLog.Error("Error trying to close the codec session, {0}", e.Message); } } try { request = new CodecRequest(_address, "/xmlapi/session/begin", _username, _password) { RequestType = RequestType.Post }; response = Dispatch(request); #if DEBUG Debug.WriteInfo("Received headers for session begin:\r\n" + response.Header); #endif if (response.Code == 401) { CloudLog.Error("Error logging into Cisco Codec at \"{0}\" 401 - Unauthorized", _address); return(false); } if (response.Code == 204) { if (!response.Header.ContainsHeaderValue("Set-Cookie")) { CloudLog.Error("Received 204 for Session ID but response headers contained no Cookie"); return(false); } Debug.WriteSuccess("Codec Set-Cookie received", response.Header["Set-Cookie"]); CloudLog.Notice("Codec Set-Cookie received\r\n{0}", response.Header["Set-Cookie"]); var match = Regex.Match(response.Header["Set-Cookie"].Value, @"(.*?)=(.*?);"); if (match.Groups[1].Value != "SecureSessionId") { CloudLog.Error("Received 204 for Session ID but response headers contained no SessionId"); return(false); } _sessionId = match.Groups[2].Value; CloudLog.Info("Codec received new Session Id OK"); return(true); } } catch (Exception e) { CloudLog.Error("Error trying to get a session ID from Cisco Codec, {0}", e.Message); return(false); } return(false); }