void StartCECTest() { _CECDevice.CEC_Err_Changed += (state) => { CrestronConsole.PrintLine("{2} CEC Err Changed State: {0}, {1}", state, _CECDevice.CEC_Err_fb, _DM_RMC_4KZ_100_C_1G.Name); }; _CECDevice.Receive_CEC_Message_Changed += (message) => { CrestronConsole.PrintLine("{2} Receive CEC Message: {0}, {1}", message, _CECDevice.Receive_CEC_Message_fb, _DM_RMC_4KZ_100_C_1G.Name); }; CrestronConsole.AddNewConsoleCommand(SendCECMessage, "TCECHDMIMessageRxDMRX", "Sends CEC Message Through DM Receiver", ConsoleAccessLevelEnum.AccessOperator); }
public CallHistory(CiscoCodec codec, int limit) { this.Codec = codec; CommandArgs args = new CommandArgs(); args.Add("Filter", "All"); args.Add("DetailLevel", "Full"); args.Add("Limit", limit); XDocument xml; try { xml = Codec.SendCommand("Command/CallHistory/Get", args); if (xml == null) { ErrorLog.Error("Error getting Call History from codec, xml == null"); } } catch (Exception e) { ErrorLog.Exception("Error getting Call history data", e); return; } #if DEBUG CrestronConsole.PrintLine("Callhistory: \r\n{0}", xml.ToString()); #endif foreach (XElement item in xml.Root.Elements().Elements("Entry")) { CallHistoryItem call = new CallHistoryItem(Codec, int.Parse(item.Element("CallHistoryId").Value), int.Parse(item.Element("CallId").Value)); calls.Add(call.ID, call); if (item.Element("CallbackNumber") != null) { call.CallbackNumber = item.Element("CallbackNumber").Value; } if (item.Element("RemoteNumber") != null) { call.RemoteNumber = item.Element("RemoteNumber").Value; } if (item.Element("DisplayName") != null) { call.DisplayName = item.Element("DisplayName").Value; } if (item.Element("Direction") != null) { call.Direction = (CallDirection)Enum.Parse( typeof(CallDirection), item.Element("Direction").Value, false); } if (item.Element("CallType") != null) { call.Type = (CallType)Enum.Parse( typeof(CallType), item.Element("CallType").Value, false); } if (item.Element("OccurrenceType") != null) { call.OccurrenceType = (CallOccurrenceType)Enum.Parse( typeof(CallOccurrenceType), item.Element("OccurrenceType").Value, false); } if (item.Element("Protocol") != null) { call.Protocol = item.Element("Protocol").Value; } if (item.Element("StartTime") != null) { call.StartTime = DateTime.Parse(item.Element("StartTime").Value); } if (item.Element("EndTime") != null) { call.EndTime = DateTime.Parse(item.Element("EndTime").Value); } if (item.Element("DisconnectCause") != null) { call.DisconnectCause = item.Element("DisconnectCause").Value; } if (item.Element("DisconnectCauseType") != null) { call.DisconnectCauseType = (CallDisconnectCauseType)Enum.Parse( typeof(CallDisconnectCauseType), item.Element("DisconnectCauseType").Value, false); } } }
/// <summary> /// Disconnect from the Pushbullet Websocket /// </summary> public void Disconnect() { wsc.Disconnect(); CrestronConsole.PrintLine("Websocket disconnected. \r\n"); }
/// <summary> /// CCDDisplay Plugin device constructor for ISerialComport transport /// </summary> /// <param name="key"></param> /// <param name="name"></param> /// <param name="config"></param> /// <param name="display">Loaded and initialized instance of CCD Display driver instance</param> public RVCDisplayDevice(string key, string name, RVCDisplayConfig config, RoomViewConnectedDisplay display) : base(key, name) { Debug.Console(0, this, "Constructing new {0} instance", name); _config = config; _display = display; StatusFeedback = new IntFeedback(() => (int)CommunicationMonitor.Status); Feedbacks.Add(StatusFeedback); VolumeLevelFeedback = new IntFeedback(() => { return((int)_display.VolumeFeedback.UShortValue); }); MuteFeedback = new BoolFeedback(() => _display.MuteOnFeedback.BoolValue); Feedbacks.Add(VolumeLevelFeedback); Feedbacks.Add(MuteFeedback); CommunicationMonitor = new CrestronGenericBaseCommunicationMonitor(this, _display, 12000, 30000); for (uint i = 1; i <= _display.SourceSelectFeedbackSigs.Count; i++) { string sourceName = "input" + i.ToString(); /// CompactFramework fix for inline Actions and using iterator variables uint sourceIndex = i; RoutingInputPort inputPort = new RoutingInputPort(sourceName, eRoutingSignalType.AudioVideo, eRoutingPortConnectionType.Hdmi, new Action(() => _display.SourceSelectSigs[sourceIndex].BoolValue = true), this) { FeedbackMatchObject = sourceIndex }; _display.SourceSelectSigs[sourceIndex].UserObject = inputPort; InputPorts.Add(inputPort); } CrestronConsole.AddNewConsoleCommand((s) => { StringBuilder sb = new StringBuilder(); sb.AppendLine("Driver Information:"); sb.AppendFormat("\tDevice ID: {0}\r\n", _display.DeviceIdStringFeedback.StringValue); sb.AppendFormat("\tFirmware: {0}\r\n", _display.FirmwareVersionFeedback.StringValue); sb.AppendFormat("\tName: {0}\r\n", _display.ProjectorNameFeedback.StringValue); sb.AppendFormat("\tDescription: {0}\r\n", _display.Description); sb.AppendFormat("\tStatus: {0}\r\n", _display.StatusMessageFeedback.StringValue); sb.AppendFormat("\tLamp: {0}\r\n", _display.LampHoursFeedback.UShortValue); sb.AppendFormat("\tLamp (text): {0}\r\n", _display.LampHoursTextFeedback.StringValue); CrestronConsole.ConsoleCommandResponse("{0}", sb.ToString()); }, Key + "INFO", "Print Driver Info", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand((s) => { StringBuilder sb = new StringBuilder(); sb.AppendLine("State:"); sb.AppendFormat("\tName: {0}\r\n", _display.Name); sb.AppendFormat("\tID: {0}\r\n", _display.ID); sb.AppendFormat("\tOnline: {0}\r\n", _display.IsOnline?"Online":"Offline"); sb.AppendFormat("\tPower: {0}\r\n", _display.PowerOnFeedback.BoolValue?"ON":"OFF"); sb.AppendFormat("\tCooling: {0}\r\n", _display.CoolingDownFeedback.BoolValue ? "ON" : "OFF"); sb.AppendFormat("\tWarming: {0}\r\n", _display.WarmingUpFeedback.BoolValue ? "ON" : "OFF"); sb.AppendFormat("\tMute: {0}\r\n", _display.MuteOnFeedback.BoolValue ? "ON" : "OFF"); sb.AppendFormat("\tVolume: {0}\r\n", _display.VolumeFeedback.UShortValue); sb.AppendFormat("\tLamp: {0}\r\n", _display.LampHoursFeedback.UShortValue); CrestronConsole.ConsoleCommandResponse("{0}", sb.ToString()); }, Key + "STATE", "Print display state", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand((s) => { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Current Input: {0}\r\n", _display.CurrentSourceFeedback.StringValue); sb.AppendFormat("Inputs:\r\n"); for (uint i = 1; i <= _display.SourceSelectFeedbackSigs.Count; i++) { string sourceName = _display.SourceNameTextFeedbackSigs[i].StringValue; if (String.IsNullOrEmpty(sourceName) || String.IsNullOrEmpty(sourceName.Trim())) { break; } sb.AppendFormat("\t{0}: {1}\r\n", sourceName, _display.SourceSelectFeedbackSigs[i].BoolValue ? "ON" : ""); } CrestronConsole.ConsoleCommandResponse(sb.ToString()); }, Key + "INPUTS", "Display Driver Inputs", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand((s) => { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Input Ports:\r\n"); foreach (var inputPort in InputPorts) { //uint sourceSelectIndex = _display.SourceSelectSigs.FirstOrDefault<BoolInputSig>(sig => sig.UserObject == inputPort).Number; uint sourceSelectIndex = 0; for (uint i = 1; i <= _display.SourceSelectSigs.Count; i++) { if (_display.SourceSelectSigs[i].UserObject == inputPort) { sourceSelectIndex = i; break; } } sb.AppendFormat("\t{0}: {1}\r\n", inputPort.Key, _display.SourceNameTextFeedbackSigs[sourceSelectIndex].StringValue); } CrestronConsole.ConsoleCommandResponse(sb.ToString()); }, Key + "ROUTINGPORTS", "Display Driver Routing Ports", ConsoleAccessLevelEnum.AccessOperator); }
public void ProcessRequest(HttpCwsContext context) { try { // Only respond to POST requests made to the listen URL's path if (parent.listenUrl.Path == context.Request.Url.AbsolutePath) { if (context.Request.HttpMethod == "POST") { // GET the individual relay to observe its updated state HttpClientRequest req = new HttpClientRequest(); string linkString = context.Request.Headers["Link"]; // The notification POST request contains a link to the updated resource in the Link header. // in compliance with the RESTful WebHooks standard at // https://webhooks.pbworks.com/w/page/13385128/RESTful%20WebHooks // This URL will be nested between the '<' and '>' characters, // as described in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link int startIndex = linkString.IndexOf('<') + 1; int endIndex = linkString.IndexOf('>'); string linkUrlString = linkString.Substring(startIndex, endIndex - startIndex); UrlParser relayUrl = new UrlParser(linkUrlString); req.Url = relayUrl; req.RequestType = RequestType.Get; HttpHeader acceptHeader = new HttpHeader("Accept", "application/vnd.collection+json"); req.Header.AddHeader(acceptHeader); req.FinalizeHeader(); HttpClientResponse res = parent.client.Dispatch(req); int rlyID; string newState = ""; if (res.Code == 200) { JObject item = JsonConvert.DeserializeObject <JObject>(res.ContentString); rlyID = (int)item["collection"]["items"][0]["data"][0]["value"]; newState = (string)item["collection"]["items"][0]["data"][1]["value"]; } else { CrestronConsole.PrintLine("Failed to get individual relay"); return; } // log the notification message to console CrestronConsole.PrintLine("NOTIFICATION: Relay #" + rlyID + "'s state changed to " + newState); // respond to notification with 200 OK context.Response.StatusCode = 200; context.Response.StatusDescription = "OK"; context.Response.End(); } else { context.Response.StatusCode = 405; context.Response.StatusDescription = "Method Not Allowed"; context.Response.End(); } } else // ignore all other URLs besides the listener URL { CrestronConsole.PrintLine("Sending back a 404"); context.Response.StatusCode = 404; context.Response.StatusDescription = "Not Found"; context.Response.End(); } } catch (Exception e) { try { // Respond with error message context.Response.StatusCode = 500; context.Response.StatusDescription = "Internal Server Error"; context.Response.End(); CrestronConsole.PrintLine("Error in ProcessRequest: " + e.Message); } catch (Exception ex) { CrestronConsole.PrintLine("ProcessRequest unable to send error response: " + ex.Message); } } finally { ErrorLog.Notice("Served response to " + context.Request.UserHostName); } }
protected override void OnReceive(byte[] buffer, int count) { for (var i = 0; i < count; i++) { var b = buffer[i]; byte nextByte = 0; if (i < buffer.Length) { nextByte = buffer[i + 1]; } if (b == 13) { // check the next byte may also be 13 in which this one maybe the checksum if (nextByte == 13) { b = nextByte; _bytes[_byteIndex] = b; _byteIndex++; } // Copy bytes to new array with length of packet and ignoring the CR. var copiedBytes = new Byte[_byteIndex]; Array.Copy(_bytes, copiedBytes, _byteIndex); _byteIndex = 0; var chk = 0; for (var i1 = 1; i1 < (copiedBytes.Length - 1); i1++) { chk = chk ^ copiedBytes[i1]; } #if DEBUG CrestronConsole.Print("NEC Rx: "); Tools.PrintBytes(copiedBytes, 0, copiedBytes.Length, false); #endif if (copiedBytes.Length > 0 && chk == copiedBytes.Last()) { if (ReceivedData != null) { ReceivedData(copiedBytes); } } else if (copiedBytes.Length > 0) { ErrorLog.Warn("NEC Display Rx: \"{0}\"", Tools.GetBytesAsReadableString(copiedBytes, 0, copiedBytes.Length, true)); ErrorLog.Warn("NEC Display Rx - Checksum Error, chk = 0x{0}, byteIndex = {1}, copiedBytes.Length = {2}", chk.ToString("X2"), _byteIndex, copiedBytes.Length); #if DEBUG CrestronConsole.PrintLine("NEC Display Rx - Checksum Error, chk = 0x{0}, byteIndex = {1}, copiedBytes.Length = {2}", chk.ToString("X2"), _byteIndex, copiedBytes.Length); #endif } } else { _bytes[_byteIndex] = b; _byteIndex++; } } }
static Scheduler() { CrestronConsole.AddNewConsoleCommand(ClearEventsFromGroup, "ClearAllEvents", "Clears all scheduled events for this group", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ListAllEventGroups, "ListAllEventGroups", "Lists all the event groups by key", ConsoleAccessLevelEnum.AccessOperator); }
private static void InternalWrite(Type classType, string fmt, params object[] args) { using (_debugFormatterLock.AquireLock()) CrestronConsole.Print(_formatter.Format(classType.Name + " - " + string.Format(fmt, args))); }
public void Post() { try { if (RequireLogin(false)) { return; } var data = JToken.Parse(Request.ContentString); switch (Request.PathArguments["method"]) { case "runcmd": var cmd = data["command"].Value <string>(); var reply = string.Empty; CrestronConsole.SendControlSystemCommand(cmd, ref reply); WriteResponse(new { @command = cmd, @reply = reply.Trim() }); break; case "config": switch (data["method"].Value <string>()) { case "save": var configData = data["configdata"]; try { System.SetConfig(configData); } catch (Exception e) { var error = new { @error = true, @title = "Error", @message = e.Message + "\r\n" + e.StackTrace }; WriteResponse(error); return; } WriteResponse(new { @error = false, @title = "Success", @message = "Config has been saved!" }); return; case "loadtemplate": try { System.LoadConfigTemplate(data["systemid"].Value <string>()); WriteResponse(new { @error = false, @title = "Success", @message = "Config has been created, check config and restart!" }); } catch (Exception e) { WriteResponse(new { @error = true, @title = "Error", @message = e.Message + "\r\n" + e.StackTrace }); } break; case "reset": System.FactoryReset(); WriteResponse(new { @error = false, @title = "Success", @message = "NVRAM has been cleared and system will now reboot!" }); break; default: HandleError(400, "Bad Request", "Unknown API method for config path"); return; } break; case "systemmonitor": switch (data["method"].Value <string>()) { case "reset_maximums": Crestron.SimplSharpPro.Diagnostics.SystemMonitor.ResetMaximums(); break; case "start": SystemMonitor.Start(); break; case "stop": SystemMonitor.Stop(); break; default: HandleError(400, "Bad Request", "Unknown API method for systemmonitor path"); return; } break; case "av": RoomBase room; switch (data["method"].Value <string>()) { case "select_source": room = System.Rooms[data["room"].Value <uint>()]; var sourceId = data["source"].Value <uint>(); var source = sourceId == 0 ? null : System.Sources[sourceId]; room.Source = source; WriteResponse(new { @error = false, @title = "Success", @message = string.Format("Source \"{0}\" has now been selected in Room \"{1}\"", source == null ? "NONE" : source.Name, room.Name) }); break; case "power_off": room = System.Rooms[data["room"].Value <uint>()]; room.PowerOff(false, PowerOfFEventType.UserRequest); WriteResponse(new { @error = false, @title = "Success", @message = string.Format("Room \"{0}\" has been requested to power off", room.Name) }); break; default: HandleError(400, "Bad Request", "Unknown API method for av path"); return; } break; default: HandleNotFound(); break; } } catch (Exception e) { HandleError(e); } }
/// <summary> /// Pulls all the bulbs and their current state from the bridge /// </summary> public void ProcBulbs(string jsondata) { try { JObject json = JObject.Parse(jsondata); HueBridge.HueBulbs.Clear(); uint hue; uint sat; uint ct; uint bri; string colormode; string type; string name; string manufacturer; string uid; string swver; bool reachable; string model; bool on; foreach (var bulb in json) { string id = bulb.Key; type = ""; name = ""; manufacturer = ""; uid = ""; swver = ""; reachable = false; model = ""; on = false; if (json[id]["state"].SelectToken("on") != null) { on = (bool)json[id]["state"]["on"]; } if (json[id]["state"].SelectToken("reachable") != null) { reachable = (bool)json[id]["state"]["reachable"]; } if (json[id].SelectToken("type") != null) { type = (string)json[id]["type"]; } if (json[id].SelectToken("name") != null) { name = (string)json[id]["name"]; } if (json[id].SelectToken("modelid") != null) { model = (string)json[id]["modelid"]; } if (json[id].SelectToken("manufacturername") != null) { manufacturer = (string)json[id]["manufacturername"]; } if (json[id].SelectToken("uniqueid") != null) { uid = (string)json[id]["uniqueid"]; } if (json[id].SelectToken("swversion") != null) { swver = (string)json[id]["swversion"]; } HueBridge.HueBulbs.Add(id, new HueBulb() { On = on, Type = type, Name = name, Model = model, Manufacturer = manufacturer, Uid = uid, SwVer = swver, Reachable = reachable }); if (json[id]["state"].SelectToken("bri") != null) { bri = (uint)json[id]["state"]["bri"]; HueBridge.HueBulbs[id].Bri = bri; } if (json[id]["state"].SelectToken("colormode") != null) { colormode = (string)json[id]["state"]["colormode"]; HueBridge.HueBulbs[id].ColorMode = colormode; if (json[id]["state"].SelectToken("hue") != null) { hue = (uint)json[id]["state"]["hue"]; HueBridge.HueBulbs[id].Hue = hue; } if (json[id]["state"].SelectToken("sat") != null) { sat = (uint)json[id]["state"]["sat"]; HueBridge.HueBulbs[id].Sat = sat; } if (json[id]["state"].SelectToken("ct") != null) { ct = (uint)json[id]["state"]["ct"]; HueBridge.HueBulbs[id].Ct = ct; } } } /* * foreach (var bulb in HueBridge.HueBulbs) * { * CrestronConsole.PrintLine("Bulb Name: {0}, Bulb ID: {1}", bulb.Name, bulb.Id); * } */ BulbNum = (ushort)HueBridge.HueBulbs.Count; CrestronConsole.PrintLine("{0} Bulbs discovered", BulbNum); if (Authorized == 1) { HueBridge.GetBridgeInfo("groups"); } } catch (Exception e) { CrestronConsole.PrintLine("Error getting bulbs: {0}", e); } }
/// <summary> /// Pulls all the scenes from the bridge and assigns them to their appropriate room based on the assigned bulbs /// </summary> public void ProcScenes(string jsondata) { try { JObject json = JObject.Parse(jsondata); string id = ""; string name = ""; string load = ""; foreach (var scene in json) { id = scene.Key; name = (string)json[id]["name"]; if (json[id]["lights"].HasValues) { load = (string)json[id]["lights"][0]; } else { load = ""; //CrestronConsole.PrintLine("load is null"); } foreach (KeyValuePair <string, HueGroup> entry in HueBridge.HueGroups) { if (entry.Value.Loads != null && load != "") { if (entry.Value.Loads.Contains((load))) { for (int y = 1; y < 20; y++) { if (entry.Value.SceneName[y] == null) { //CrestronConsole.PrintLine("SceneName: {0}, with D: {1}", name, id); entry.Value.SceneName[y] = name; entry.Value.SceneID[y] = id; break; } } } } } } CrestronConsole.PrintLine("{0} Scenes discovered", json.Count); HueOnline = 1; HueBridge.Populated = true; GrpName = new String[50]; BlbName = new String[50]; int i = 1; foreach (KeyValuePair <string, HueGroup> entry in HueBridge.HueGroups) { GrpName[i] = entry.Value.Name; i++; } i = 1; foreach (KeyValuePair <string, HueBulb> entry in HueBridge.HueBulbs) { BlbName[i] = entry.Value.Name; i++; } //HueBridge.GetBridgeInfo("sensors"); OnInitComplete(); } catch (Exception e) { CrestronConsole.PrintLine("Error getting scenes: {0}", e); } }
public void Get() { if (RequireLogin(true)) { return; } try { var ms = new MemoryStream(); var appNumber = InitialParametersClass.ApplicationNumber; var commands = new[] { "hostname", "mycrestron", "showlicense", "osd", "uptime", "ver -v", "ver all", "uptime", "time", "timezone", "sntp", "showhw", "ipconfig /all", "progregister", "progcomments:1", "progcomments:2", "progcomments:3", "progcomments:4", "progcomments:5", "progcomments:6", "progcomments:7", "progcomments:8", "progcomments:9", "progcomments:10", "proguptime:1", "proguptime:2", "proguptime:3", "proguptime:4", "proguptime:5", "proguptime:6", "proguptime:7", "proguptime:8", "proguptime:9", "proguptime:10", "ssptasks:1", "ssptasks:2", "ssptasks:3", "ssptasks:4", "ssptasks:5", "ssptasks:6", "ssptasks:7", "ssptasks:8", "ssptasks:9", "ssptasks:10", "appstat -p:" + appNumber, "taskstat", "ramfree", "cpuload", "cpuload", "cpuload", "showportmap -all", "ramfree", "showdiskinfo", "ethwdog", "iptable -p:all -t", "who", "netstat", "threadpoolinfo", "autodiscover query tableformat", "reportcresnet", }; using (var zip = new ZipFile()) { var directory = new DirectoryInfo(@"\NVRAM"); foreach (var file in directory.GetFiles()) { zip.AddFile(file.FullName, @"\NVRAM Root"); } directory = new DirectoryInfo(SystemBase.AppStoragePath); foreach (var file in directory.GetFiles()) { zip.AddFile(file.FullName, string.Format("\\NVRAM for App {0}", InitialParametersClass.ApplicationNumber.ToString("D2"))); } var diagnosticsData = new StringWriter(); foreach (var message in System.StatusMessages) { diagnosticsData.WriteLine("{0}: {2} {1}", message.MessageLevel, message.MessageString, message.SourceDeviceName); } zip.AddEntry("diagnostics.txt", diagnosticsData.ToString()); directory = new DirectoryInfo(@"/Sys/PLog/CurrentBoot"); foreach (var file in directory.GetFiles()) { zip.AddFile(file.FullName, @"\CurrentBootLogs"); } directory = new DirectoryInfo(@"/Sys/PLog/PreviousBoot"); foreach (var file in directory.GetFiles()) { zip.AddFile(file.FullName, @"\PreviousBootLogs"); } var statusData = new MemoryStream(); var sw = new StreamWriter(statusData); foreach (var command in commands) { sw.WriteLine("Console Cmd: {0}", command); var response = string.Empty; CrestronConsole.SendControlSystemCommand(command, ref response); sw.WriteLine(response); } statusData.Position = 0; zip.AddEntry(@"processor_status.txt", statusData); zip.Save(ms); } Request.Response.Header.ContentType = MimeMapping.GetMimeMapping(".zip"); Request.Response.ContentSource = ContentSource.ContentStream; var hostname = CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType( EthernetAdapterType.EthernetLANAdapter)); Request.Response.Header.AddHeader(new HttpHeader("content-disposition", string.Format("attachment; filename=processor_report_{0}_{1}.zip", hostname, DateTime.Now.ToString("yyyyMMddTHHmmss")))); ms.Position = 0; Request.Response.ContentStream = ms; Request.Response.CloseStream = true; } catch (Exception e) { HandleError(e); } }
private object ConnectionThreadProcess(object o) { try { while (true) { var connectCount = 0; while (_remainConnected && !Connected) { if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { Thread.Sleep(5000); continue; } connectCount++; var result = _client.ConnectToServer(); if (result == SocketErrorCodes.SOCKET_OK) { CrestronConsole.PrintLine("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo); try { OnConnect(); OnStatusChanged(SocketStatusEventType.Connected); } catch (Exception e) { CloudLog.Exception(e); } break; } if (connectCount <= 2 || connectCount > 5) { continue; } if (connectCount == 5) { CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background", GetType().Name, _client.AddressClientConnectedTo); } CrestronEnvironment.AllowOtherAppsToRun(); } _adapterType = _client.EthernetAdapter; while (true) { var dataCount = _client.ReceiveData(); if (dataCount <= 0) { CrestronConsole.PrintLine("{0} Disconnected!", GetType().Name); try { OnStatusChanged(SocketStatusEventType.Disconnected); OnDisconnect(); } catch (Exception e) { CloudLog.Exception(e); } if (_remainConnected) { Thread.Sleep(2000); if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST) { CloudLog.Warn("{0} Ethernet Link Lost! - sleeping thread until back up", GetType().Name); } break; } CrestronConsole.PrintLine("Exiting {0}", Thread.CurrentThread.Name); return(null); } //CrestronConsole.PrintLine("{0} {1} bytes in buffer", GetType().Name, dataCount); try { OnReceive(_client.IncomingDataBuffer, dataCount); } catch (Exception e) { CloudLog.Exception(e); } CrestronEnvironment.AllowOtherAppsToRun(); Thread.Sleep(0); } } } catch (Exception e) { if (_remainConnected) { CloudLog.Exception("Error in handler thread while connected / connecting", e); } return(null); } }
public static void Start(System_Monitor SystemMonitor) { _SystemMonitor = SystemMonitor; _SystemMonitor.CIP_RX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CIP_RX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.CIP_RX_Count_F); }; _SystemMonitor.CIP_StatisticsEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CIP_StatisticsEnable_F_Changed: {0}, {1}", value, _SystemMonitor.CIP_StatisticsEnable_F); }; _SystemMonitor.CIP_TotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CIP_TotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.CIP_TotalCount_F); }; _SystemMonitor.CIP_TX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CIP_TX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.CIP_TX_Count_F); }; _SystemMonitor.CPU_Utilization_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CPU_Utilization_F_Changed: {0}, {1}", value, _SystemMonitor.CPU_Utilization_F); }; _SystemMonitor.CPU_UtilizationEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CPU_UtilizationEnable_F_Changed: {0}, {1}", value, _SystemMonitor.CPU_UtilizationEnable_F); }; _SystemMonitor.CresnetRX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetRX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetRX_Count_F); }; _SystemMonitor.CresnetRX_UtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetRX_UtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetRX_UtilizationCount_F); }; _SystemMonitor.CresnetStatisticsEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetStatisticsEnable_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetStatisticsEnable_F); }; _SystemMonitor.CresnetTotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetTotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetTotalCount_F); }; _SystemMonitor.CresnetTotalUtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetTotalUtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetTotalUtilizationCount_F); }; _SystemMonitor.CresnetTX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresnetTX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetTX_Count_F); }; _SystemMonitor.CresneTX_UtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: CresneTX_UtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.CresnetTX_UtilizationCount_F); }; _SystemMonitor.ErrorLogErrorCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: ErrorLogErrorCount_F_Changed: {0}, {1}", value, _SystemMonitor.ErrorLogErrorCount_F); }; _SystemMonitor.ErrorLogNoticeCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: ErrorLogNoticeCount_F_Changed: {0}, {1}", value, _SystemMonitor.ErrorLogNoticeCount_F); }; _SystemMonitor.ErrorLogStatisticsEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: ErrorLogStatisticsEnable_F_Changed: {0}, {1}", value, _SystemMonitor.ErrorLogStatisticsEnable_F); }; _SystemMonitor.ErrorLogWarningCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: ErrorLogWarningCount_F_Changed: {0}, {1}", value, _SystemMonitor.ErrorLogWarningCount_F); }; _SystemMonitor.HeapFree_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: HeapFree_F_Changed: {0}, {1}", value, _SystemMonitor.HeapFree_F); }; _SystemMonitor.HeapFreeMin_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: HeapFreeMin_F_Changed: {0}, {1}", value, _SystemMonitor.HeapFreeMin_F); }; _SystemMonitor.MaxCIP_RX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCIP_RX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCIP_RX_Count_F); }; _SystemMonitor.MaxCIP_TotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCIP_TotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCIP_TotalCount_F); }; _SystemMonitor.MaxCIP_TX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCIP_TX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCIP_TX_Count_F); }; _SystemMonitor.MaxCPU_Utilization_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCPU_Utilization_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCPU_Utilization_F); }; _SystemMonitor.MaxCresnetRX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetRX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetRX_Count_F); }; _SystemMonitor.MaxCresnetRX_UtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetRX_UtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetRX_UtilizationCount_F); }; _SystemMonitor.MaxCresnetTotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetTotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetTotalCount_F); }; _SystemMonitor.MaxCresnetTotalUtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetTotalUtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetTotalUtilizationCount_F); }; _SystemMonitor.MaxCresnetTX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetTX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetTX_Count_F); }; _SystemMonitor.MaxCresnetTX_UtilizationCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxCresnetTX_UtilizationCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxCresnetTX_UtilizationCount_F); }; _SystemMonitor.MaxProcesses_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxProcesses_F_Changed: {0}, {1}", value, _SystemMonitor.MaxProcesses_F); }; _SystemMonitor.MaxTCP_RX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxTCP_RX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxTCP_RX_Count_F); }; _SystemMonitor.MaxTCP_TotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxTCP_TotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.MaxTCP_TotalCount_F); }; _SystemMonitor.MaxTCP_TX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: MaxTCP_TX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.MaxTCP_TX_Count_F); }; _SystemMonitor.NumProcesses_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: NumProcesses_F_Changed: {0}, {1}", value, _SystemMonitor.NumProcesses_F); }; _SystemMonitor.ProcessStatisticsEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: ProcessStatisticsEnable_F_Changed: {0}, {1}", value, _SystemMonitor.ProcessStatisticsEnable_F); }; _SystemMonitor.SysmonStarted_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: SysmonStarted_F_Changed: {0}, {1}", value, _SystemMonitor.SysmonStarted_F); }; _SystemMonitor.TCP_RX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: TCP_RX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.TCP_RX_Count_F); }; _SystemMonitor.TCP_StatisticsEnable_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: TCP_StatisticsEnable_F_Changed: {0}, {1}", value, _SystemMonitor.TCP_StatisticsEnable_F); }; _SystemMonitor.TCP_TotalCount_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: TCP_TotalCount_F_Changed: {0}, {1}", value, _SystemMonitor.TCP_TotalCount_F); }; _SystemMonitor.TCP_TX_Count_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: TCP_TX_Count_F_Changed: {0}, {1}", value, _SystemMonitor.TCP_TX_Count_F); }; _SystemMonitor.TotalHeapSpace_F_Changed += (value) => { CrestronConsole.PrintLine("Sys Mon: TotalHeapSpace_F_Changed: {0}, {1}", value, _SystemMonitor.TotalHeapSpace_F); }; CrestronConsole.AddNewConsoleCommand(Sysmon, "TSysmon", "Start/Stop System Monitor for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ResetMax, "TResetMax", "Reset Max Stats for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ProcessStatiscs, "TProcessStatistics", "Start/Stop Process Statistics for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(CresnetStatistics, "TCresnetStatistics", "Start/Stop Cresnet Statistics for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(TCPStatistics, "TTCPStatistics", "Start/Stop TCP Statistics for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(CIPStatistics, "TCIPStatistics", "Start/Stop CIP Statistics for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(CPUUtilization, "TCPUUtilization", "Start/Stop CPU Utilization for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ErrorLogStatistics, "TErrorLogStatistics", "Start/Stop Error Log Statistics for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(UpdateInterval, "TUpdateInterval", "Start/Stop Update Interval for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(CresnetStatisticsMode, "TCresnetStatisticsMode", "Set Cresnet Statistics Mode for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(TCPStatisticsMode, "TTCPStatisticsMode", "Set TCP Statistics Mode for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(CIPStatisticsMode, "TCIPStatisticsMode", "Set CIP Statistics Mode for System Monitor", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(GetStatsState, "TGetStatsState", "Get enable/disable statuses", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(GetAllStats, "TGetAllStats", "Get All Statistics", ConsoleAccessLevelEnum.AccessOperator); _SystemMonitor.StartSysmon(); _SystemMonitor.ProcessStatisticsEnable(); _SystemMonitor.CresnetStatisticsEnable(); _SystemMonitor.TCP_StatisticsEnable(); _SystemMonitor.CIP_StatisticsEnable(); _SystemMonitor.CPU_UtilizationEnable(); _SystemMonitor.ErrorLogStatisicsEnable(); }
/// <summary> /// ControlSystem Constructor. Starting point for the SIMPL#Pro program. /// Use the constructor to: /// * Initialize the maximum number of threads (max = 400) /// * Register devices /// * Register event handlers /// * Add Console Commands /// /// Please be aware that the constructor needs to exit quickly; if it doesn't /// exit in time, the SIMPL#Pro program will exit. /// /// You cannot send / receive data in the constructor /// </summary> public ControlSystem() : base() { try { Thread.MaxNumberOfUserThreads = 20; //System.Security.Cryptography.SHA1.Create(); //register device myKeypad = new C2nCbdP(0x25, this); myKeypad.ButtonStateChange += (device, args) => { var btn = args.Button; var uo = btn.UserObject; CrestronConsole.PrintLine("Event sig: {0}, Type: {1}, State: {2}", btn.Number, btn.GetType(), btn.State); if (btn.State == eButtonState.Pressed) { switch (btn.Number) { case 1: if (myDimmer.DinLoads[2].LevelOut.UShortValue > 0) { myDimmer.DinLoads[2].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(0f); myKeypad.Feedbacks[1].State = false; } else { myDimmer.DinLoads[2].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(100f); myKeypad.Feedbacks[1].State = true; } break; case 2: if (myDimmer.DinLoads[3].LevelOut.UShortValue > 0) { myDimmer.DinLoads[3].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(0f); myKeypad.Feedbacks[2].State = false; } else { myDimmer.DinLoads[3].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(100f); myKeypad.Feedbacks[2].State = true; } break; case 5: myRelay.SwitchedLoads[1].FullOn(); myRelay.SwitchedLoads[2].FullOff(); break; case 6: myRelay.SwitchedLoads[2].FullOn(); myRelay.SwitchedLoads[1].FullOff(); break; case 7: myRelay.SwitchedLoads[3].FullOn(); myRelay.SwitchedLoads[4].FullOff(); break; case 8: myRelay.SwitchedLoads[4].FullOn(); myRelay.SwitchedLoads[3].FullOff(); break; default: break; } } }; if (myKeypad.Register() != eDeviceRegistrationUnRegistrationResponse.Success) { CrestronConsole.PrintLine(" Unable to register for keypad "); CrestronConsole.PrintLine("myKeypad {0} failed registration. Cause: {1}", 0x25, myKeypad.RegistrationFailureReason); ErrorLog.Error("myKeypad {0} failed registration. Cause: {1}", 0x25, myKeypad.RegistrationFailureReason); } else { CrestronConsole.PrintLine(" Keypad successfully registered "); } myKeypad2 = new C2niCb(0x26, this); myKeypad2.ButtonStateChange += (device, args) => { var btn = args.Button; var uo = btn.UserObject; CrestronConsole.PrintLine("Event keypad 2 sig: {0}, Type: {1}, State: {2}", btn.Number, btn.GetType(), btn.State); if (btn.State == eButtonState.Pressed) { switch (btn.Number) { case 2: if (myDimmer.DinLoads[1].LevelOut.UShortValue > 0) { myDimmer.DinLoads[1].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(0f); myKeypad2.Feedbacks[1].State = false; myKeypad2.Feedbacks[2].State = false; } else { myDimmer.DinLoads[1].LevelIn.UShortValue = SimplSharpDeviceHelper.PercentToUshort(100f); myKeypad2.Feedbacks[1].State = true; myKeypad2.Feedbacks[2].State = true; } break; case 9: myRelay.SwitchedLoads[5].FullOn(); myRelay.SwitchedLoads[6].FullOff(); break; case 11: myRelay.SwitchedLoads[6].FullOn(); myRelay.SwitchedLoads[5].FullOff(); break; default: break; } } }; if (myKeypad2.Register() != eDeviceRegistrationUnRegistrationResponse.Success) { CrestronConsole.PrintLine(" Unable to register for keypad2 "); CrestronConsole.PrintLine("myKeypad2 {0} failed registration. Cause: {1}", 0x26, myKeypad2.RegistrationFailureReason); ErrorLog.Error("myKeypad2 {0} failed registration. Cause: {1}", 0x26, myKeypad2.RegistrationFailureReason); } else { CrestronConsole.PrintLine(" Keypad2 successfully registered "); } myDimmer = new Din1DimU4(0x0A, this); // Now register the event handlers myDimmer.OverrideEventHandler += (device, overrideEvent) => { switch (overrideEvent) { case eOverrideEvents.External: CrestronConsole.PrintLine(" Device reports external override event. State is {0} ", myDimmer.InExternalOverrideFeedback.BoolValue); break; case eOverrideEvents.Manual: CrestronConsole.PrintLine(" Device reports manual override event. State is {0} ", myDimmer.InManualOverrideFeedback.BoolValue); break; } }; myDimmer.OnlineStatusChange += (currentDevice, args) => CrestronConsole.PrintLine(" Din1DimU4 state {0} ", args.DeviceOnLine ? "Online" : "Offline"); myDimmer.BaseEvent += (device, args) => { //CrestronConsole.PrintLine("dimmer {0}", args.EventId); switch (args.EventId) { case DinLoadBaseClass.LevelOutFeedbackEventId: CrestronConsole.PrintLine(" Level out changed for output {0} ", args.Index); CrestronConsole.PrintLine(" Value of load is {0} ", myDimmer.DinLoads[(uint)args.Index].LevelOut.UShortValue); //myDimmer.DinLoads[(uint)args.Index].LevelIn.UShortValue = myDimmer.DinLoads[(uint)args.Index].LevelOut.UShortValue; break; case DinLoadBaseClass.NoAcPowerFeedbackEventId: CrestronConsole.PrintLine(" NoAcPowerFeedbackEventId fired. State is {0} ", myDimmer.NoAcPower.BoolValue); break; } }; // Need to set parameters before we register the device foreach (DinDimmableLoad dimmableLoad in myDimmer.DinLoads) { dimmableLoad.ParameterDimmable = eDimmable.No; } // Register the device now if (myDimmer.Register() != eDeviceRegistrationUnRegistrationResponse.Success) { CrestronConsole.PrintLine(" Unable to register for dimmer "); CrestronConsole.PrintLine("myDimmer {0} failed registration. Cause: {1}", 0x0A, myDimmer.RegistrationFailureReason); ErrorLog.Error("myDimmer {0} failed registration. Cause: {1}", 0x0A, myDimmer.RegistrationFailureReason); } else { CrestronConsole.PrintLine(" Dimmer successfully registered "); } myRelay = new Din8Sw8i(0x92, this); myRelay.OverrideEventHandler += (device, overrideEvent) => { switch (overrideEvent) { case eOverrideEvents.External: CrestronConsole.PrintLine(" Device relay reports external override event. State is {0} ", myRelay.InExternalOverrideFeedback.BoolValue); break; case eOverrideEvents.Manual: CrestronConsole.PrintLine(" Device relay reports manual override event. State is {0} ", myRelay.InManualOverrideFeedback.BoolValue); break; } }; myRelay.OnlineStatusChange += (currentDevice, args) => CrestronConsole.PrintLine(" Din8Sw8i state {0} ", args.DeviceOnLine ? "Online" : "Offline"); myRelay.BaseEvent += (device, args) => { CrestronConsole.PrintLine("relay {0}", args.EventId); switch (args.EventId) { //case DinLoadBaseClass.LevelOutFeedbackEventId: // CrestronConsole.PrintLine(" relay Level out changed for output {0} ", args.Index); // //CrestronConsole.PrintLine(" Value of load is {0} ", myRelay.DinLoads[(uint)args.Index].LevelOut.UShortValue); // break; //case DinLoadBaseClass.NoAcPowerFeedbackEventId: // CrestronConsole.PrintLine(" NoAcPowerFeedbackEventId fired. State is {0} ", myRelay.NoAcPower.BoolValue); // break; } }; myRelay.LoadStateChange += (lightingObject, args) => { CrestronConsole.PrintLine("load relay {0}", args.EventId); // use this structure to react to the different events switch (args.EventId) { case LoadEventIds.IsOnEventId: CrestronConsole.PrintLine(" relay Level out changed for output {0} ", args.Load.Number); CrestronConsole.PrintLine(" Value of load is {0} ", myRelay.SwitchedLoads[args.Load.Number].IsOn); //xp.BooleanInput[1].BoolValue = !lampDimmer.DimmingLoads[1].IsOn; //xp.BooleanInput[2].BoolValue = lampDimmer.DimmingLoads[1].IsOn; break; case LoadEventIds.LevelChangeEventId: //xp.UShortInput[1].UShortValue = lampDimmer.DimmingLoads[1].LevelFeedback.UShortValue; break; case LoadEventIds.LevelInputChangedEventId: //xp.UShortInput[1].CreateRamp(lampDimmer.DimmingLoads[1].Level.RampingInformation); break; default: break; } }; // Register the device now if (myRelay.Register() != eDeviceRegistrationUnRegistrationResponse.Success) { CrestronConsole.PrintLine(" Unable to register for relay "); CrestronConsole.PrintLine("myRelay {0} failed registration. Cause: {1}", 0x92, myRelay.RegistrationFailureReason); ErrorLog.Error("myRelay {0} failed registration. Cause: {1}", 0x92, myRelay.RegistrationFailureReason); } else { CrestronConsole.PrintLine(" Relay successfully registered "); } //Subscribe to the controller events (System, Program, and Ethernet) CrestronEnvironment.SystemEventHandler += systemEventType => { switch (systemEventType) { case (eSystemEventType.DiskInserted): //Removable media was detected on the system break; case (eSystemEventType.DiskRemoved): //Removable media was detached from the system break; case (eSystemEventType.Rebooting): //The system is rebooting. //Very limited time to preform clean up and save any settings to disk. break; } }; CrestronEnvironment.ProgramStatusEventHandler += programStatusEventType => { switch (programStatusEventType) { case (eProgramStatusEventType.Paused): //The program has been paused. Pause all user threads/timers as needed. break; case (eProgramStatusEventType.Resumed): //The program has been resumed. Resume all the user threads/timers as needed. break; case (eProgramStatusEventType.Stopping): //The program has been stopped. //Close all threads. //Shutdown all Client/Servers in the system. //General cleanup. //Unsubscribe to all System Monitor events break; } }; CrestronEnvironment.EthernetEventHandler += ethernetEventArgs => { switch (ethernetEventArgs.EthernetEventType) { //Determine the event type Link Up or Link Down case (eEthernetEventType.LinkDown): //Next need to determine which adapter the event is for. //LAN is the adapter is the port connected to external networks. if (ethernetEventArgs.EthernetAdapter == EthernetAdapterType.EthernetLANAdapter) { // } break; case (eEthernetEventType.LinkUp): if (ethernetEventArgs.EthernetAdapter == EthernetAdapterType.EthernetLANAdapter) { } break; } }; //my console command CrestronConsole.AddNewConsoleCommand(Hello, "hello", "hello command", ConsoleAccessLevelEnum.AccessOperator); } catch (Exception e) { ErrorLog.Error("Error in the constructor: {0}", e.Message); } }
public void PrintSomething(String str) { CrestronConsole.Print(str); }
// My Console Command Delegate void Hello(string response) { CrestronConsole.ConsoleCommandResponse("Hello world: {0}", response.ToUpper()); }
public void RoomList(ushort LSorH) { //debug //CrestronConsole.PrintLine("Looking for room list value: {0}", LSorH); switch (LSorH) { case 0: { try { for (int i = 0; i < Obj.Rooms.Count; i++) { HazLightID[i] = Obj.Rooms[i].Lights.LightEquipmentID; } } catch { CrestronConsole.PrintLine("Failed to set up Light/HVAC/Shades"); } break; } case 1: { try { for (int i = 0; i < Obj.Rooms.Count; i++) { HazShadeID[i] = Obj.Rooms[i].Shades.ShadeEquipmentID; } } catch { CrestronConsole.PrintLine("Failed to set up Light/HVAC/Shades"); } break; } case 2: { try { for (int i = 0; i < Obj.Rooms.Count; i++) { HazHVACID[i] = Obj.Rooms[i].HVAC.HVACEquipmentID; } } catch { CrestronConsole.PrintLine("Failed to set up Light/HVAC/Shades"); } break; } default: { CrestronConsole.PrintLine("Got to End Nothing"); break; } } }
static void ChangeInputName(string Options) { string MessageHelp = "TInputName InputNo(1-10) Name"; var commands = Regex.Matches(Options, "[\\w]+|\\\"[^\\\"]*\\\""); int InputNumber; string Name; try { Name = commands[1].Value; InputNumber = int.Parse(commands[0].Value); } catch (Exception) { CrestronConsole.ConsoleCommandResponse(MessageHelp); return; } if (InputNumber > 0 && InputNumber <= 10) { CrestronConsole.ConsoleCommandResponse("CMD:Changing input {0} name to : {1}", InputNumber, Name); switch (InputNumber) { case 1: _DeviceControl.Input_1_Name(Name); break; case 2: _DeviceControl.Input_2_Name(Name); break; case 3: _DeviceControl.Input_3_Name(Name); break; case 4: _DeviceControl.Input_4_Name(Name); break; case 5: _DeviceControl.Input_5_Name(Name); break; case 6: _DeviceControl.Input_6_Name(Name); break; case 7: _DeviceControl.Input_7_Name(Name); break; case 8: _DeviceControl.Input_8_Name(Name); break; case 9: _DeviceControl.Input_9_Name(Name); break; case 10: _DeviceControl.Input_10_Name(Name); break; default: break; } } else { CrestronConsole.ConsoleCommandResponse(MessageHelp); } }
/// <summary> /// LIGHT helper console function. /// </summary> /// <param _name="cmd">command _name</param> private void ConsoleCommandLightGroup(string cmd) { const string re = @"\G(""((""""|[^""])+)""|(\S+)) *"; const string usage = "Usage:\r\n\t lightgroup <id>|<name> [<ON|OFF|<intensity>>|save <name>|load <name>|list]"; var ms = Regex.Matches(cmd, re); string[] args = ms.Cast <Match>().Select(m => Regex.Replace(m.Groups[2].Success ? m.Groups[2].Value : m.Groups[4].Value, @"""""", @"""")).ToArray(); if (args.Length >= 1) { LightGroup lightGroup = _lightGroups.Find(g => g.Name == args[0]); if (lightGroup == null) { try { uint id = Convert.ToUInt32(args[0]); lightGroup = _lightGroups.Find(g => g.Id == id); if (lightGroup == null) { throw new ArgumentOutOfRangeException("args[0]"); } } catch (Exception) { CrestronConsole.ConsoleCommandResponse("LightGroup with id or name \"{0}\" can't be found", args[0]); return; } } if (args.Length >= 2) { switch (args[1]) { case "ON": lightGroup.Muted = false; break; case "OFF": lightGroup.Muted = true; break; case "save": //preset = lightMaster.SavePreset(); //CrestronConsole.ConsoleCommandResponse(preset); if (args.Length >= 3 && !String.IsNullOrEmpty(args[2])) { string presetName = args[2]; LightsPresetManager.Save(presetName, lightGroup); } else { CrestronConsole.ConsoleCommandResponse("ERROR: Preset name is invalid"); } break; case "load": if (args.Length >= 3 && !String.IsNullOrEmpty(args[2]) && LightsPresetManager.PresetFileExists(args[2], lightGroup)) { string presetName = args[2]; LightsPresetManager.Load(presetName, lightGroup); } else { CrestronConsole.ConsoleCommandResponse("ERROR: Preset could not be found"); } break; case "list": StringBuilder response = new StringBuilder("Presets for " + lightGroup.Name + "\r\n"); foreach (string presetName in LightsPresetManager.List(lightGroup)) { response.AppendLine(presetName); } CrestronConsole.ConsoleCommandResponse(response.ToString()); break; default: try { ushort intensity = Convert.ToUInt16(args[1]); lightGroup.Intensity = intensity; } catch (Exception) { CrestronConsole.ConsoleCommandResponse("\"{0}\" can't be converted to ether ON, OFF or Intensity value.", args[1]); return; } break; } } else // args.Length == 1 { StringBuilder response = new StringBuilder(); response.AppendLine("LightGroup:"); response.AppendLine(lightGroup.ToString()); CrestronConsole.ConsoleCommandResponse(response.ToString()); } } else { CrestronConsole.ConsoleCommandResponse(usage); } }
public static void PrintBytes(byte[] bytes, int length, bool showReadable) { CrestronConsole.PrintLine(GetBytesAsReadableString(bytes, length, showReadable)); }
/// <summary> /// LIGHT helper console function. /// </summary> /// <param _name="cmd">command _name</param> private void ConsoleCommandLights(string cmd) { const string re = @"\G(""((""""|[^""])+)""|(\S+)) *"; const string usage = "Usage:\r\n\t lights <id> [ON|OFF|<intensity>|preset <presetId> <newPresetName>]"; var ms = Regex.Matches(cmd, re); string[] args = ms.Cast <Match>().Select(m => Regex.Replace(m.Groups[2].Success ? m.Groups[2].Value : m.Groups[4].Value, @"""""", @"""")).ToArray(); if (args.Length >= 1) { LightFixture lightFixture; try { uint id = Convert.ToUInt32(args[0]); lightFixture = GetLightFixtureById(id); if (lightFixture == null) { throw new ArgumentOutOfRangeException("args[0]"); } } catch (Exception) { CrestronConsole.ConsoleCommandResponse("LightFixture can't be found by id \"{0}\"", args[0]); return; } if (args.Length >= 2) { switch (args[1]) { case "ON": lightFixture.Muted = false; break; case "OFF": lightFixture.Muted = true; break; case "preset": CrestronConsole.ConsoleCommandResponse(lightFixture.SavePreset()); break; case "load": break; default: try { ushort intensity = Convert.ToUInt16(args[1]); lightFixture.Intensity = intensity; } catch (Exception) { CrestronConsole.ConsoleCommandResponse("\"{0}\" can't be converted to ether ON, OFF or Intensity value.", args[1]); return; } break; } } else // args.Length == 1 { StringBuilder response = new StringBuilder(); response.AppendLine("LightFixture:"); response.AppendLine(lightFixture.ToString()); CrestronConsole.ConsoleCommandResponse(response.ToString()); } } else { CrestronConsole.ConsoleCommandResponse(usage); } }
// Event handler called every time the listener receives an HTTP request private void listener_ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args) { CrestronConsole.PrintLine(""); CrestronConsole.PrintLine("Received " + args.Context.Request.HttpMethod + " request from " + args.Context.Request.UserHostName); }
public void Initialize() { try { if (LightsConfigManager.Initialize() != LightsConfigManager.eConfigInitializationSuccessFailureReasons.Success) { var configObj = new LightsConfig(); configObj.Profiles = new Dictionary <string, DMXFixtureProfileConfig>(2) { { "ETC Source Four LED Studio HD", new DMXFixtureProfileConfig() { Id = 1, Name = "ETC Source Four LED Studio HD", DMXChannels = new Dictionary <DMXChannel, ushort>() { { DMXChannel.Intensity, 1 }, { DMXChannel.WhitePoint, 2 }, } } }, { "Elation Satura Profile Basic", new DMXFixtureProfileConfig() { Id = 2, Name = "Elation Satura Profile Basic", DMXChannels = new Dictionary <DMXChannel, ushort>() { { DMXChannel.Intensity, 15 }, { DMXChannel.Pan, 1 }, { DMXChannel.Tilt, 2 }, { DMXChannel.Zoom, 20 }, { DMXChannel.Iris, 18 }, { DMXChannel.Focus, 19 }, { DMXChannel.Blade1, 21 }, { DMXChannel.Blade1Rotate, 22 }, { DMXChannel.Blade2, 23 }, { DMXChannel.Blade2Rotate, 24 }, { DMXChannel.Blade3, 25 }, { DMXChannel.Blade3Rotate, 26 }, { DMXChannel.Blade4, 27 }, { DMXChannel.Blade4Rotate, 28 }, }, } }, { "Elation Satura Profile Standard", new DMXFixtureProfileConfig() { Id = 3, Name = "Elation Satura Profile Standard", DMXChannels = new Dictionary <DMXChannel, ushort>() { { DMXChannel.Intensity, 17 }, { DMXChannel.Pan, 1 }, { DMXChannel.PanFine, 2 }, { DMXChannel.Tilt, 3 }, { DMXChannel.TiltFine, 4 }, { DMXChannel.Zoom, 22 }, { DMXChannel.Iris, 20 }, { DMXChannel.Focus, 21 }, { DMXChannel.Blade1, 23 }, { DMXChannel.Blade1Rotate, 24 }, { DMXChannel.Blade2, 25 }, { DMXChannel.Blade2Rotate, 26 }, { DMXChannel.Blade3, 27 }, { DMXChannel.Blade3Rotate, 28 }, { DMXChannel.Blade4, 29 }, { DMXChannel.Blade4Rotate, 30 }, }, } }, }; configObj.Lights = new Dictionary <string, List <DMXFixtureConfig> >(3) { { "Podium", new List <DMXFixtureConfig>(2) { new DMXFixtureConfig() { Id = 1, Name = "South #1", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 11 }, new DMXFixtureConfig() { Id = 2, Name = "North #4", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 41 }, } }, { "Stage", new List <DMXFixtureConfig>(4) { new DMXFixtureConfig() { Id = 3, Name = "South #2", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 21 }, new DMXFixtureConfig() { Id = 4, Name = "South #3", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 31 }, new DMXFixtureConfig() { Id = 5, Name = "North #5", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 51 }, new DMXFixtureConfig() { Id = 6, Name = "North #6", Profile = configObj.Profiles["ETC Source Four LED Studio HD"], BaseDMXChannel = 61 }, } }, { "PTZ", new List <DMXFixtureConfig>(2) { new DMXFixtureConfig() { Id = 7, Name = "South", Profile = configObj.Profiles["Elation Satura Profile Standard"], BaseDMXChannel = 256, }, new DMXFixtureConfig() { Id = 8, Name = "North", Profile = configObj.Profiles["Elation Satura Profile Standard"], BaseDMXChannel = 310, }, } }, }; LightsConfigManager.CreateNewConfig(configObj); } if (LightsPresetManager.Initialize() != LightsPresetManager.ePresetInitializationSuccessFailureReasons.Success) { ErrorLog.Error("Failed to initialize presets"); } foreach (string group in LightsConfigManager.Groups) { //List<DMXFixture> groupDmxFixtures = new List<DMXFixture>(LightsConfigManager.GroupFixtures(group).Count); LightGroup lightGroup = new LightGroup((uint)(_lightGroups.Count + 1), group); _lightGroups.Add(lightGroup); foreach (DMXFixtureConfig dmxFixtureConfig in LightsConfigManager.GroupFixtures(group)) { DMXFixture dmxFixture; switch (dmxFixtureConfig.Profile.Name) { case "ETC Source Four LED Studio HD": dmxFixture = new DMXFixture(lightGroup, dmxFixtureConfig, _transport); break; case "Elation Satura Profile Standard": dmxFixture = new DMXPTZFixture(lightGroup, dmxFixtureConfig, _transport); break; default: dmxFixture = new DMXFixture(lightGroup, dmxFixtureConfig, _transport); break; } } } CrestronConsole.AddNewConsoleCommand(ConsoleCommandLightGroups, "lightgroups", "List light groups. Use \"LIGHTGROUPS ?\" for more info.", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ConsoleCommandLightGroup, "lightgroup", "Light master commands. Use \"LIGHTGROUP ?\" for more info.", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ConsoleCommandLights, "lights", "Lighting commands. Use \"LIGHTS ?\" for more info.", ConsoleAccessLevelEnum.AccessOperator); CrestronConsole.AddNewConsoleCommand(ConsoleCommandTest, "test", "TEST commands. Use \"TEST ?\" for more info.", ConsoleAccessLevelEnum.AccessOperator); ErrorLog.Notice(">>> LightsControl: initialized successfully"); } catch (Exception e) { ErrorLog.Error(">>> LightControl: Error in InitializeSystem: {0}\r\n{1}", e.Message, e.StackTrace); } }
// Subscribe to a random relay port on the server control system. The RelayMonitor will print notifications // to the console when this relay changes state public void Subscribe(string serverHostname) { try { if (subscribed) { CrestronConsole.PrintLine("The monitor can only subscribe to one relay at a time. Unsubscribe first"); return; } // point serverAPIUrl at the root of the remote CWS server serverAPIUrl = new UrlParser("http://" + serverHostname + "/cws/api/"); // GET the relay collection and derive the number of relays // available on the control system from the response HttpClientRequest req = new HttpClientRequest(); UrlParser collectionUrl = new UrlParser(serverAPIUrl, "relays"); // complete URL = baseUrl + relativeUrl req.Url = collectionUrl; req.RequestType = RequestType.Get; HttpHeader acceptHeader = new HttpHeader("Accept", "application/vnd.collection+json"); req.Header.AddHeader(acceptHeader); req.FinalizeHeader(); HttpClientResponse res = client.Dispatch(req); if (res.Code == 200) { CrestronConsole.PrintLine("Received GET response for the relay collection"); string json = res.ContentString; JObject collection = JsonConvert.DeserializeObject <JObject>(json); JArray list = (JArray)collection["collection"]["items"]; int relayCount = list.Count; Random rnd = new Random(); rlyID = rnd.Next(1, relayCount + 1); CrestronConsole.PrintLine("Server control system has " + relayCount + " relays. Subscribing to relay #" + rlyID + "..."); // Subscribe the the web-hook for the Relay #rlyID req = new HttpClientRequest(); UrlParser webhookUrl = new UrlParser(serverAPIUrl, "relays/" + rlyID + "/web-hooks"); req.Url = webhookUrl; req.RequestType = RequestType.Post; // add the Content-Type and Notification-Type headers as required by the RESTful WebHooks standard HttpHeaders headers = new HttpHeaders(); headers.SetHeaderValue("Content-Type", "text/uri-list"); // webhook expects POST body to contain a single URL headers.SetHeaderValue("Notification-Type", "UPDATED"); // monitor wants to know when relay state is changed req.Header = headers; req.FinalizeHeader(); req.ContentString = listenUrl.ToString(); res = client.Dispatch(req); if (res.Code == 201) // successful POST, subscription resource has been created { subscriptionUrl = new UrlParser(res.Header["Location"].Value); // save the obscure URL to the new subscription resource subscribed = true; CrestronConsole.PrintLine("Subscribed to Relay #" + rlyID); CrestronConsole.PrintLine("Subscription resource URL: " + subscriptionUrl); } else { CrestronConsole.PrintLine("Failed to subscribe to " + rlyID); } // Must call Dispose on the HttpClientResponse object to end this HTTP session res.Dispose(); } else { CrestronConsole.PrintLine("Failed to get relay collection"); return; } } catch (Exception e) { CrestronConsole.PrintLine("Error in Subscribe(): " + e.Message); } finally { } }
protected object ReceiveBufferProcess(object obj) { Byte[] bytes = new Byte[1000]; int byteIndex = 0; while (true) { try { byte b = RxQueue.Dequeue(); // If find byte = CR if (b == 13) { // Copy bytes to new array with length of packet and ignoring the CR. Byte[] copiedBytes = new Byte[byteIndex]; Array.Copy(bytes, copiedBytes, byteIndex); byteIndex = 0; int chk = 0; for (int i = 1; i < (copiedBytes.Length - 1); i++) { chk = chk ^ copiedBytes[i]; } if (chk == copiedBytes.Last()) { #if DEBUG //CrestronConsole.Print("NEC Rx: "); //Tools.PrintBytes(copiedBytes, copiedBytes.Length); #endif if (ReceivedPacket != null) { ReceivedPacket(this, copiedBytes); } CrestronEnvironment.AllowOtherAppsToRun(); } else { #if DEBUG CrestronConsole.PrintLine("NEC Display Rx - Checksum Error"); #endif ErrorLog.Error("NEC Display Rx - Checksum Error"); } } else { bytes[byteIndex] = b; byteIndex++; } } catch (Exception e) { if (e.Message != "ThreadAbortException") { ErrorLog.Exception("Error in NEC Rx Thread Handler", e); } } } }
private Action <string> ValidateWriter(Action <string> writer) { return(writer != null ? writer : msg => CrestronConsole.ConsoleCommandResponse(msg)); }
protected void printDebugLine(string debugText) { CrestronConsole.PrintLine("httpToSignal service: " + debugText); }
public void Close() { CrestronConsole.PrintLine("Connection {0}, total bytes recieved [{1}]", ClientIndex, _totalBytesReceived); }
public void EICSignalHandler(BasicTriList currentDevice, SigEventArgs args) { CrestronConsole.PrintLine("[+] Signal Received : {0}", currentDevice.ToString()); Sig signal = args.Sig; switch (signal.Type) { // Digital case (eSigType.Bool): CrestronConsole.PrintLine("[+] Digital: {0}", signal.ToString()); // Occupancy Detected Signal if (signal.Number == (uint)eSignalDigitalID.Occupancy_Detected) { CrestronConsole.PrintLine("[+] Occupancy Detected: {0}", signal.BoolValue); if (signal.BoolValue) { // Start receiving occupancy information. New room object to store info. _room = new Room(); _room.setOccupied(); } else { // Done receiving occupancy information. Store the room state property.updateRoom(_room); TxPropertyStatus(property); } } // Vacancy Detected Signal if (signal.Number == (uint)eSignalDigitalID.Vacancy_Detected) { CrestronConsole.PrintLine("[+] Vacancy Detected: {0}", signal.BoolValue); if (signal.BoolValue) { // Start receiving vacancy information. New room object to store info. _room = new Room(); _room.setVacant(); } else { // Done receiving vacancy information. Store the room state property.updateRoom(_room); } } break; // Analog case (eSigType.UShort): CrestronConsole.PrintLine("[+] Analog: {0}", signal.ToString()); break; // Serial case (eSigType.String): CrestronConsole.PrintLine("[+] Serial: {0}", signal.ToString()); // Motion_Location$ Signal if (signal.Number == (uint)eSignalSerialID.Motion_Location) { CrestronConsole.PrintLine("[+] Motion Location: {0}", signal.StringValue); _room.Name = signal.StringValue; } break; default: CrestronConsole.PrintLine("[+] Unknown: {0}", signal.ToString()); break; } }