private void AmOnOnlineStatusChange(GenericBase currentDevice, OnlineOfflineEventArgs args) { if (!args.DeviceOnLine) { CloudLog.Warn("{0} is offline!", currentDevice.ToString()); } if (args.DeviceOnLine && currentDevice is AmX00) { try { ((AmX00)currentDevice).DisplayControl.DisableAutomaticRouting(); } catch (Exception e) { CloudLog.Exception(e); } } try { if (DeviceCommunicatingChange != null) { DeviceCommunicatingChange(this, args.DeviceOnLine); } } catch (Exception e) { CloudLog.Exception(e); } }
private void AssetCommsAlertTimerProcess(object userSpecific) { var itemsToRemove = new List <FusionStaticAsset>(); foreach (var kvp in _assetCommsStatus) { var asset = kvp.Key; var info = kvp.Value; if (!info.ShouldRaiseAlert) { continue; } if (info.Communicating) { CloudLog.Info("Notifying Fusion asset \"{0}\" is back online", asset.ParamAssetName); } else { CloudLog.Warn("Notifying Fusion asset \"{0}\" is now offline", asset.ParamAssetName); } itemsToRemove.Add(asset); asset.Connected.InputSig.BoolValue = info.Communicating; asset.AssetError.InputSig.StringValue = !info.Communicating ? "3:Device is offline" : "0:Device is online"; } foreach (var assetKey in itemsToRemove) { _assetCommsStatus.Remove(assetKey); } }
public void Connect() { if (_client != null && _client.IsConnected) { CloudLog.Warn("{0} already connected", GetType().Name); return; } _reconnect = true; var info = new KeyboardInteractiveConnectionInfo(_address, 22, _username); info.AuthenticationPrompt += OnPasswordPrompt; _client = new SshClient(info); _client.ErrorOccurred += (sender, args) => CrestronConsole.PrintLine("ErrorOccurred: {0}", args.Exception.Message); _client.HostKeyReceived += (sender, args) => CrestronConsole.PrintLine("HostKeyReceived: {1}, can trust = {0}", args.CanTrust, args.HostKeyName); _sshProcess = new Thread(SshCommsProcess, null, Thread.eThreadStartOptions.CreateSuspended) { Name = "Tesira SSH Comms Handler", Priority = Thread.eThreadPriority.HighPriority }; _sshProcess.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); } }
internal void HandleError(OnHttpRequestArgs args, int code, string title, string message) { //#if DEBUG CloudLog.Warn("Webserver Error {0}, {1}, Path: {2}\r\n{3}", code, title, args.Request.Path, message); //#endif try { var errorTemplate = new TemplateEngine(Assembly.GetExecutingAssembly(), "WebApp.Templates.error.html", "Error" + code, false); errorTemplate.Context.Add("error_code", code.ToString()); errorTemplate.Context.Add("error_title", title); errorTemplate.Context.Add("error_message", message); errorTemplate.Context["page_style_link"] = @"<link href=""/static/lib2/css/error.css"" rel=""stylesheet"">"; args.Response.Code = code; args.Response.ResponseText = title; args.Response.Header.ContentType = "text/html"; args.Response.ContentSource = ContentSource.ContentString; args.Response.ContentString = errorTemplate.Render(); } catch (Exception e) { CloudLog.Exception(e); } try { //args.Response.FinalizeHeader(); } 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(); }
internal SnapshotController(QsysCore core, JToken data) : base(core, data) { var count = 10; try { count = int.Parse(Properties["dataset_count"]); } catch (Exception e) { CloudLog.Warn("Error in Snapshot Controller ctor, {0}, defaulting to size of 10", e.Message); } for (var i = 1; i <= count; i++) { var control = RegisterControl(string.Format("load.{0}", i)); if (control == null) { break; } RegisterControl(string.Format("match.{0}", i)).ValueChange += OnValueChange; RegisterControl(string.Format("last.{0}", i)).ValueChange += OnValueChange; } }
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); } }
protected SocketErrorCodes Send(byte[] bytes, int index, int count) { var result = _client.SendData(bytes, index, count); if (result != SocketErrorCodes.SOCKET_OK) { CloudLog.Warn("Could not send data in {0}, {1}", GetType().Name, result); } return(result); }
private void Callback(HttpClientResponse response, HTTP_CALLBACK_ERROR error) { try { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { CloudLog.Warn("Cannot communicate with AvediaServer to discover receivers"); return; } if (response.Code != 200) { CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code); return; } var data = JArray.Parse(response.ContentString); #if true Debug.WriteInfo(Debug.AnsiPurple + data.ToString(Formatting.Indented) + Debug.AnsiReset); #endif foreach ( var device in data.Where( d => d["type"].Value <string>() == "Media Player" || d["type"].Value <string>() == "Receiver") ) { if (this.Any(d => d.Id == device["id"].Value <string>())) { this[device["id"].Value <string>()].UpdateInfo(device); } else { Receiver receiver = null; try { receiver = new Receiver(_server, device); } catch (Exception e) { CloudLog.Exception(e, "Error loading receiver object from data"); } if (receiver == null) { continue; } _receivers.Add(receiver); OnReceiverDiscovered(receiver, receiver.Id, receiver.Name); } } } catch (Exception e) { CloudLog.Exception(e); } }
public void Disconnect() { if (_client == null || !_client.IsConnected) { CloudLog.Warn("{0} is not connected", GetType().Name); return; } _reconnect = false; _client.Disconnect(); }
public void StopRecording(int contentId, string name) { var requestData = new { name, schedule = new { @stop = DateTime.Now, } }; var json = JToken.FromObject(requestData); var request = new ServerRequest(_server.HostNameOrIpAddress, "/api/content/recording/scheduled/" + contentId, json.ToString(), RequestType.Put, (response, error) => { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { CloudLog.Warn("Cannot communicate with AvediaServer to get recordings"); OnRecordingsUpdated(new RecordingsUpdatedEventArgs { EventType = RecordingUpdatedEventType.StopRecording, RequestFailed = true, FailReason = "Could not get response from server" }); return; } if (response.Code != 200) { CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code); OnRecordingsUpdated(new RecordingsUpdatedEventArgs { EventType = RecordingUpdatedEventType.StopRecording, RequestFailed = true, FailReason = "Server responded with " + response.Code + " error", }); return; } var data = JToken.Parse(response.ContentString).First; var id = data["Id"].Value <int>(); CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code); OnRecordingsUpdated(new RecordingsUpdatedEventArgs { EventType = RecordingUpdatedEventType.StopRecording, RequestFailed = false, RecordingId = id }); }); _server.QueueRequest(request); }
public void Send(string line) { if (Connected) { _sendQueue.Enqueue(line); //_threadWait.Set(); } else { CloudLog.Warn("Could not send \"{0}\" to codec. No Connection", line); } }
/// <summary> /// Boots all users off the solstice, clears posts and returns to splash screen /// </summary> public void Boot() { var uri = string.Format("http://{0}/api/control/boot?password={1}", _address, _password); _client.GetAsync(uri, (userobj, error) => { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { CloudLog.Warn("Error trying to send end session command to Solstice Pod at \"{0}\"", _address); } }); }
internal int SendCommandAsync(CodecCommand command, CodecCommandResponse callback) { var xml = command.XmlString; #if DEBUG CrestronConsole.PrintLine("Command: ({0} bytes)\r\n{1}", xml.Length, xml); #endif var id = _httpsClient.PutXmlAsync(xml, response => { #if DEBUG CrestronConsole.PrintLine("Command response received with id:{0}", response.Request.Id); #endif var call = _commandCallbacks[response.Request.Id]; _commandCallbacksLock.Enter(); _commandCallbacks.Remove(response.Request.Id); _commandCallbacksLock.Leave(); if (response.Code == 200 && response.Xml != null) { try { var result = response.Xml.Element("Command").Elements().First(); #if DEBUG CrestronConsole.PrintLine("Request {0} {1} = {2}", response.Request.Id, result.XName.LocalName, result.Attribute("status").Value); #endif call(response.Request.Id, result.Attribute("status").Value == "OK", result); return; } catch (Exception e) { CloudLog.Exception(e); } } else if (response.Code == 401) { CloudLog.Warn( "Received 401 code in {0}.SendCommandAsync(CodecCommand command, CodecCommandResponse callback)", GetType().Name); } call(response.Request.Id, false, null); }); _commandCallbacksLock.Enter(); _commandCallbacks[id] = callback; _commandCallbacksLock.Leave(); #if DEBUG CrestronConsole.PrintLine("Sending command \"{0}\" with id:{1}", command.Command, id); #endif return(id); }
public void Send(string line) { if (Connected) { #if DEBUG Debug.WriteWarn("Tesira Enqueued Message", line); #endif _sendQueue.Enqueue(line); } else { CloudLog.Warn("Could not send \"{0}\" to Tesira. No Connection", line); } }
public static void GetAppUpdates() { if (string.IsNullOrEmpty(_serverAddress)) { throw new Exception("No update server found"); } var attemptCount = 0; while (attemptCount < 2) { attemptCount++; try { var assembly = Assembly.GetExecutingAssembly(); var appName = assembly.GetName(); var url = string.Format("http://{0}/api/software/app_updates?app={1}", _serverAddress, appName.Name); var response = _httpClient.GetAsync(url).Await(); if (response.StatusCode != HttpStatusCode.OK) { CloudLog.Error("Error getting software update, {0}", response.StatusCode); return; } var data = JToken.Parse(response.Content.ReadAsStringAsync().Await()); _updates = data["response"]["files"].Select(fileData => fileData.ToObject <AppFileInfo>()) .Where(f => new Version(f.Version) != appName.Version) .ToList(); return; } catch (Exception e) { if (attemptCount == 1) { CloudLog.Warn("Could not Get App Updates, disposing old httpclient and making new one"); _httpClient.Dispose(); _httpClient = new HttpClient(); } else { throw new Exception( string.Format("Could not get information request from update server, {0}", e.Message), e); } } } }
private void FusionAssetOnDeviceCommunicatingChange(IDevice device, bool communicating) { if (_programStopping) { return; } foreach (var asset in (from fusionAsset in _fusionAssets where device == fusionAsset.Value select Fusion.UserConfigurableAssetDetails[fusionAsset.Key].Asset).OfType <FusionStaticAsset>()) { if (!communicating) { CloudLog.Warn( "Fusion monitoring status change for asset \"{0}\", Communicating = {1}, adding to queue and will wait 150 seconds before notifying Fusion", device.Name, communicating); } else { CloudLog.Info( "Fusion monitoring status change for asset \"{0}\", Communicating = {1}, adding to queue and will wait 150 seconds before notifying Fusion", device.Name, communicating); } _assetCommsStatus[asset] = new FusionAssetCommsStatus(communicating, DateTime.Now, GetTimeDelayForDeviceTimeout(device)); if (!(device is IPowerDevice)) { asset.PowerOn.InputSig.BoolValue = communicating; } if (!communicating) { SendFusionErrorMessage(FusionErrorLevel.Error, "Asset: \"{0}\" is offline", device.Name); } else { SendFusionErrorMessage(FusionErrorLevel.Ok, "Asset: \"{0}\" is online", device.Name); asset.FusionGenericAssetSerialsAsset3.StringInput[50].StringValue = device.DeviceAddressString; asset.FusionGenericAssetSerialsAsset3.StringInput[51].StringValue = device.SerialNumber; asset.FusionGenericAssetSerialsAsset3.StringInput[52].StringValue = device.VersionInfo; } } CheckFusionAssetsForOnlineStatusAndReportErrors(); }
public void SendToAll(byte[] bytes, int offset, int count) { foreach (var connection in _connections) { var clientIndex = connection.Key; if (connection.Value == SocketStatus.SOCKET_STATUS_CONNECTED) { var result = _socket.SendData(clientIndex, bytes, offset, count); if (result != SocketErrorCodes.SOCKET_OK) { CloudLog.Warn("{0} Sending data to client index {1} received error: {2}", GetType().Name, clientIndex, result); } } } }
private void SocketOnReceivedData(string receivedString) { try { //Debug.WriteSuccess("Extron Rx", receivedString); var match = Regex.Match(receivedString, @"RcdrY(\d+)"); if (match.Success) { return; } match = Regex.Match(receivedString, @"<ChA(\d)\*ChB(\d)>\*<(\w+)>\*<(\w+)(?:\*(.+))?>\*<(\d+)(?:\*(.+))?>\*<([\d:]+)>\*<([\d:]+)(?:\*([\d:]+))?>"); if (match.Success) { try { RecordStatus = (eRecordStatus)Enum.Parse(typeof(eRecordStatus), match.Groups[3].Value, true); } catch (Exception e) { //CloudLog.Error(e.Message + " value = " + match.Groups[3].Value); } try { _storageLocation = (eStorageType)Enum.Parse(typeof(eStorageType), match.Groups[4].Value, true); } catch { _storageLocation = eStorageType.Unknown; } _bytesAvailable = long.Parse(match.Groups[6].Value) * 1000; _timer = TimeFromString(match.Groups[8].Value); _timeAvailable = TimeFromString(match.Groups[9].Value); OnStatusUpdated(this); } else { CloudLog.Warn("No match for received string: \"{0}\"", receivedString); } } catch (Exception e) { CloudLog.Exception(e); } }
public QsysChangeGroup Add(IEnumerable <QsysControl> controls) { var qsysControls = controls as QsysControl[] ?? controls.ToArray(); if (!qsysControls.Any()) { CloudLog.Warn("Cannot add controls to changegroup... array is empty"); return(null); } if (qsysControls.Any(c => c.Component != qsysControls.First().Component)) { return(null); } using (var writer = new StringWriter()) { using (var json = new JsonTextWriter(writer)) { json.WriteStartObject(); json.WritePropertyName("Id"); json.WriteValue(Id); json.WritePropertyName("Component"); json.WriteStartObject(); json.WritePropertyName("Name"); json.WriteValue(qsysControls.First().Component.Name); json.WritePropertyName("Controls"); json.WriteStartArray(); foreach (var control in qsysControls) { json.WriteStartObject(); json.WritePropertyName("Name"); json.WriteValue(control.Name); json.WriteEndObject(); } json.WriteEndArray(); json.WriteEndObject(); json.WriteEndObject(); } var args = JObject.Parse(writer.ToString()); Core.RequestAsync(OnRequestResponse, "ChangeGroup.AddComponentControl", args); } return(this); }
public void Connect() { if (_thread != null && _thread.ThreadState == Thread.eThreadStates.ThreadRunning) { CloudLog.Warn("{0}.Connect() already called and is {1}", GetType(), Connected ? "Connected" : "Connecting"); return; } _remainConnected = true; _thread = new Thread(ConnectionThreadProcess, null) { Priority = Thread.eThreadPriority.UberPriority, Name = string.Format("{0} Handler Thread", GetType().Name) }; }
private void CheckStatusTimer(object userSpecific) { if (!_threadRunning) { if (_checkStatusThread != null) { CloudLog.Warn("{0} Status Checking Thread is not responding. Aborting and Restarting!", GetType().Name); _checkStatusThread.Abort(); _checkStatusThread = null; } StartCheckingThread(); return; } _threadRunning = false; }
protected override void WillShow() { base.WillShow(); _tabs.ButtonEvent += TabsOnButtonEvent; _channelButtons.ButtonEvent += ChannelButtonsOnButtonEvent; if (_currentId == 0) { _tabs.SetInterlockedFeedback(1); _currentId = _receiverIds[1]; } Device.BooleanInput[Digitals.IptvTabsVisible].BoolValue = _receiverIds.Count > 1; TripleCare.GetChannels(ConfigManager.Config.TriplePlayServerAddress, -1, (success, channels) => { if (success && channels != null) { var channelOrder = channels .OrderBy(c => c.Number) .Take((int)_channelList.MaxNumberOfItems) .ToArray(); CloudLog.Debug("Received {0} channels from server", channelOrder.Count()); try { _channelList.ClearList(true); foreach (var channel in channelOrder) { _channelList.AddItem(channel.Name, channel, true); } _channelList.SetListSizeToItemCount(); } catch (Exception e) { CloudLog.Exception(e, "Error loading channels into list"); } } else { CloudLog.Warn("Could not load channel list from server"); } }); }
private void LightsOnButtonEvent(IButton button, ButtonEventArgs args) { if (args.EventType != ButtonEventType.Released) { return; } var roomIndex = _lightsTabButtons.First(kvp => kvp.Value == args.Collection).Key; var room = UIController.System.Rooms[roomIndex] as ARoom; try { room.RecallLightingScene(args.CollectionKey); } catch (Exception e) { CloudLog.Warn("Could not control lights, {0}", e.Message); } }
private object ReceiveDataProcessingThread(object userSpecific) { CloudLog.Info("{0} Started", Thread.CurrentThread.Name); while (!_programStopping) { var count = _socket.ReceiveData(); if (count > 0) { Debug.WriteSuccess("Visca Rx " + _socket.IPAddressLastMessageReceivedFrom, Tools.GetBytesAsReadableString(_socket.IncomingDataBuffer, 0, count, false)); } else if (count < 0) { CloudLog.Warn("{0} Received Data Count {1}", Thread.CurrentThread.Name, count); } } CloudLog.Warn("{0} Exiting", Thread.CurrentThread.Name); return(null); }
private void DeviceOnOnlineStatusChange(GenericBase currentDevice, OnlineOfflineEventArgs args) { if (!args.DeviceOnLine) { CloudLog.Warn("{0} is offline!", currentDevice.ToString()); } try { if (DeviceCommunicatingChange != null) { DeviceCommunicatingChange(this, args.DeviceOnLine); } } 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"); } }
private void Callback(HttpClientResponse response, HTTP_CALLBACK_ERROR error) { try { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { CloudLog.Warn("Cannot communicate with AvediaServer to discover channels"); return; } if (response.Code != 200) { CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code); return; } var channels = JToken.Parse(response.ContentString)["channel"].Select(channel => new Channel(_server, channel)) .ToList(); if (channels.Count > 0) { _channels.Clear(); foreach (var channel in channels) { _channels.Add(channel); } OnChannelsUpdated(this); } else { CloudLog.Warn( "AvediaServer returned no channels in API. Existing collection will remain to prevent loss of channel list."); } } catch (Exception e) { CloudLog.Exception(e); } }
private void BlindsOnButtonEvent(IButton button, ButtonEventArgs args) { if (args.EventType != ButtonEventType.Released) { return; } var key = _blindsTabButtons.First(kvp => kvp.Value == args.Collection).Key; var roomIndex = (key / 2) + (key % 2); var room = UIController.System.Rooms[roomIndex] as ARoom; var channel = key - ((roomIndex - 1) * 2); try { room.Blinds(channel, (BlindsCommand)args.CollectionKey); } catch (Exception e) { CloudLog.Warn("Could not control blinds, {0}", e.Message); } }