Exemple #1
0
        static Logger()
        {
            ConsoleServer = new ConsoleServer();
            ConsoleServer.ReceivedCommand += ConsoleServerOnReceivedCommand;
            CrestronEnvironment.ProgramStatusEventHandler += OnProgramStatusEventHandler;
            AddCommand(PrintCommandHelp, "Help", "Get list of commands", "command");
            AddCommand(TailLog, "Tail", "Tail the logger entries", "count");
            AddCommand(ConsoleLog, "Log", "Write a log entry");
            AddCommand(GetIpTable, "IPTable", "Print the IP Table for the current running program");
            AddCommand((argString, args, connection, respond) =>
            {
                respond($"Logging level is set to: {_level}");
            }, "Level", "Get the current logging level");
            AddCommand(SetStreamLevel, "LogStreamLevel", "Set the level logs stream on this connection", "level");
            AddCommand(ListAssemblies, "ListAssemblies", "List the available assemblies in the app");
            if (CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance)
            {
                AddCommand((argString, args, connection, respond) =>
                {
                    var response = string.Empty;
                    CrestronConsole.SendControlSystemCommand($"progreset -P:{InitialParametersClass.ApplicationNumber}",
                                                             ref response);
                }, "RestartApp", "Restart the running application");
                AddCommand(GetAutoDiscovery, "AutoDiscover", "Get the system autodiscovery results");
                AddCommand(RelayConsoleCommand, "Console", "Send a command to the Crestron console");
            }

            var ass = Assembly.GetExecutingAssembly().GetName();

            Highlight($"{ass.Name}.{nameof(Logger)} started, version {ass.Version}");
        }
Exemple #2
0
        private void PollUptime(object obj)
        {
            var consoleResponse = string.Empty;

            CrestronConsole.SendControlSystemCommand("uptime", ref consoleResponse);

            ParseUptime(consoleResponse);

            UptimeFeedback.FireUpdate();
            LastStartFeedback.FireUpdate();
        }
        /// <summary>
        /// Connects to the processor via SSH and restarts the program
        /// </summary>
        static void RestartProgram()
        {
            Debug.Console(0, Debug.ErrorLogLevel.Notice, "Attempting to Reset Program");

            OnStatusUpdate(eUpdateStatus.RestartingProgram);

            string response = string.Empty;

            CrestronConsole.SendControlSystemCommand(string.Format("progreset -p:{0}", InitialParametersClass.ApplicationNumber), ref response);

            Debug.Console(1, "Console Response: {0}", response);
        }
Exemple #4
0
        /// <summary>
        /// Generates the device's dump
        /// </summary>
        /// <returns></returns>
        public string GenerateDeviceDump()
        {
            string dump = string.Format("UTC date and time: {0}\n\n", DateTime.UtcNow);

            foreach (string cmd in _consoleCommands)
            {
                string res = "";
                CrestronConsole.SendControlSystemCommand(cmd, ref res);
                dump += res;
            }

            return(dump);
        }
        /// <summary>
        /// Gets the current processor info
        /// </summary>
        public void GetProcessorInfo()
        {
            OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);

            try
            {
                var processor = new ProcessorInfo();
                processor.Model              = InitialParametersClass.ControllerPromptName;
                processor.SerialNumber       = CrestronEnvironment.SystemInfo.SerialNumber;
                processor.ModuleDirectory    = InitialParametersClass.ProgramDirectory.ToString();
                processor.ProgramIdTag       = InitialParametersClass.ProgramIDTag;
                processor.DevicePlatform     = CrestronEnvironment.DevicePlatform.ToString();
                processor.OsVersion          = CrestronEnvironment.OSVersion.Version.ToString();
                processor.RuntimeEnvironment = CrestronEnvironment.RuntimeEnvironment.ToString();
                processor.LocalTimeZone      = CrestronEnvironment.GetTimeZone().Offset;

                // Does not return firmware version matching a "ver" command
                // returns the "ver -v" 'CAB' version
                // example return ver -v:
                //		RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
                //		Build: 14:05:46  Oct 09 2018 (3568.25373)
                //		Cab: 1.503.0070
                //		Applications:  1.0.6855.21351
                //		Updater: 1.4.24
                //		Bootloader: 1.22.00
                //		RMC3-SetupProgram: 1.003.0011
                //		IOPVersion: FPGA [v09] slot:7
                //		PUF: Unknown
                //Firmware = CrestronEnvironment.OSVersion.Firmware;
                //Firmware = InitialParametersClass.FirmwareVersion;

                // Use below logic to get actual firmware ver, not the 'CAB' returned by the above
                // matches console return of a "ver" and on SystemInfo page
                // example return ver:
                //		RMC3 Cntrl Eng [v1.503.3568.25373 (Oct 09 2018), #4001E302] @E-00107f4420f0
                var response = "";
                CrestronConsole.SendControlSystemCommand("ver", ref response);
                processor.Firmware     = ParseConsoleResponse(response, "Cntrl Eng", "[", "(");
                processor.FirmwareDate = ParseConsoleResponse(response, "Cntrl Eng", "(", ")");

                OnProcessorChange(processor, 0, SystemInfoConstants.ProcessorConfigChange);
            }
            catch (Exception e)
            {
                var msg = string.Format("GetProcessorInfo failed: {0}", e.Message);
                CrestronConsole.PrintLine(msg);
                //ErrorLog.Error(msg);
            }

            OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
        }
Exemple #6
0
 public virtual void Reboot()
 {
     BootStatus = "System will now reboot - Please Wait";
     foreach (var uiController in UIControllers)
     {
         uiController.InternalSystemWillRestart(false);
     }
     WillRestart  = true;
     _rebootTimer = new CTimer(specific =>
     {
         var response = string.Empty;
         CrestronConsole.SendControlSystemCommand("reboot", ref response);
     }, 2000);
 }
Exemple #7
0
 public virtual void LoadUpdate()
 {
     BootStatus = "Application will now update - Please Wait";
     foreach (var uiController in UIControllers)
     {
         uiController.InternalSystemWillRestart(true);
     }
     WillRestart  = true;
     _rebootTimer = new CTimer(specific =>
     {
         var response = string.Empty;
         CrestronConsole.SendControlSystemCommand(
             string.Format("progload -p{0}", InitialParametersClass.ApplicationNumber), ref response);
     }, 2000);
 }
 /// <summary>
 /// Gets the program uptime, by index, and passes it to S+
 /// </summary>
 /// <param name="index"></param>
 public void RefreshProgramUptimeByIndex(int index)
 {
     try
     {
         string response = "";
         CrestronConsole.SendControlSystemCommand(string.Format("proguptime:{0}", index), ref response);
         string uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
         OnStringChange(uptime, (ushort)index, SystemInfoConstants.ProgramUptimeChange);
     }
     catch (Exception e)
     {
         var msg = string.Format("RefreshProgramUptimebyIndex({0}) failed:\r{1}", index, e.Message);
         CrestronConsole.PrintLine(msg);
         //ErrorLog.Error(msg);
     }
 }
 /// <summary>
 /// Gets the processor uptime and passes it to S+
 /// </summary>
 public void RefreshProcessorUptime()
 {
     try
     {
         string response = "";
         CrestronConsole.SendControlSystemCommand("uptime", ref response);
         var uptime = ParseConsoleResponse(response, "running for", "running for", "\x0D");
         OnStringChange(uptime, 0, SystemInfoConstants.ProcessorUptimeChange);
     }
     catch (Exception e)
     {
         var msg = string.Format("RefreshProcessorUptime failed:\r{0}", e.Message);
         CrestronConsole.PrintLine(msg);
         //ErrorLog.Error(msg);
     }
 }
Exemple #10
0
        public static IEnumerable <IpTableResult> GetIpTable()
        {
            var reply = string.Empty;

            if (CrestronConsole.SendControlSystemCommand("ipt -t", ref reply) == false)
            {
                return(new IpTableResult[]
                {
                });
            }

            var matches = Regex.Matches(reply,
                                        @"\ *(\w+)\ *\|(\w+)\ *\|(\w+)\ *\|(\w+)?\ *\|(\d+)\ *\|([\d\.]+)\ *\|\ *([\w\-\ ]+)\ *?\|\ *([\w ]+)");

            return(new ReadOnlyCollection <IpTableResult>((from Match match in matches
                                                           select
                                                           new IpTableResult(int.Parse(match.Groups[1].Value.Trim(), NumberStyles.HexNumber), match.Groups[3].Value.Trim() == "ONLINE",
                                                                             int.Parse(match.Groups[5].Value.Trim()), match.Groups[6].Value.Trim(),
                                                                             match.Groups[7].Value.Trim())).ToList()));
        }
        /// <summary>
        /// Sends command to console, passes response back using string change event
        /// </summary>
        /// <param name="cmd"></param>
        public void SendConsoleCommand(string cmd)
        {
            if (string.IsNullOrEmpty(cmd))
            {
                return;
            }

            string response = "";

            CrestronConsole.SendControlSystemCommand(cmd, ref response);
            if (!string.IsNullOrEmpty(response))
            {
                if (response.EndsWith("\x0D\\x0A"))
                {
                    response.Trim('\n');
                }

                OnStringChange(response, 0, SystemInfoConstants.ConsoleResponseChange);
            }
        }
        //public static Dictionary<int, ProcessorProgramItem> Programs { get; private set; }

        public static Dictionary <int, ProcessorProgramItem> GetProcessorProgReg()
        {
            var programs = new Dictionary <int, ProcessorProgramItem>();

            for (int i = 1; i <= Global.ControlSystem.NumProgramsSupported; i++)
            {
                string response = null;
                var    success  = CrestronConsole.SendControlSystemCommand("progcomments:" + i, ref response);
                var    item     = new ProcessorProgramItem();
                if (!success)
                {
                    item.Name = "Error: PROGCOMMENTS failed";
                }
                else
                {
                    if (response.ToLower().Contains("bad or incomplete"))
                    {
                        item.Name = "";
                    }
                    else
                    {
                        var startPos = response.IndexOf("Program File");
                        var colonPos = response.IndexOf(":", startPos) + 1;
                        var endPos   = response.IndexOf(CrestronEnvironment.NewLine, colonPos);
                        item.Name   = response.Substring(colonPos, endPos - colonPos).Trim();
                        item.Exists = true;
                        if (item.Name.Contains(".dll"))
                        {
                            startPos  = response.IndexOf("Compiler Revision");
                            colonPos  = response.IndexOf(":", startPos) + 1;
                            endPos    = response.IndexOf(CrestronEnvironment.NewLine, colonPos);
                            item.Name = item.Name + "_v" + response.Substring(colonPos, endPos - colonPos).Trim();
                        }
                    }
                }
                programs[i] = item;
                Debug.Console(1, "Program {0}: {1}", i, item.Name);
            }
            return(programs);
        }
Exemple #13
0
        public override void InitializeSystem()
        {
            try
            {
                myServer = new HttpCwsServer("/api");
                myServer.ReceivedRequestEvent += new HttpCwsRequestEventHandler(myServerReceivedRequestEvent);
                myServer.Routes.Add(new HttpCwsRoute("ver")
                {
                    Name = "shversion"
                });
                myServer.Register();

                CrestronConsole.SendControlSystemCommand("progcomments:1", ref cmdResponse);
                CrestronConsole.SendControlSystemCommand("ver", ref versionResponse);

                var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);
                macAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
            }
            catch (Exception e)
            {
                ErrorLog.Error("Error in InitializeSystem: {0}", e.Message);
            }
        }
Exemple #14
0
        private IEnumerable <LogEntry> GetProgramErrorLogs(uint appNumber)
        {
            string        logfileContents = null;
            StringBuilder sb = null;

            string consoleResponse = string.Empty;

            try
            {
                if (CrestronConsole.SendControlSystemCommand("ERR\r", ref consoleResponse))
                {
                    sb = new StringBuilder(consoleResponse);
                }
            }
            catch (Exception) { /* ignore */ }

            if (sb != null)
            {
                logfileContents = FixLog(sb.ToString());
            }

            return(ParseLogEntries(appNumber, logfileContents));
        }
Exemple #15
0
        public virtual void FactoryReset()
        {
            CloudLog.Warn("FactoryReset() Called!!");

            var directory = new DirectoryInfo(AppStoragePath);

            foreach (var file in directory.GetFiles())
            {
                CloudLog.Warn("Deleting file {0}", file.FullName);
                file.Delete();
            }

            BootStatus = "Processor will now reboot - Please Wait";
            foreach (var uiController in UIControllers)
            {
                uiController.InternalSystemWillRestart(false);
            }
            WillRestart  = true;
            _rebootTimer = new CTimer(specific =>
            {
                var response = string.Empty;
                CrestronConsole.SendControlSystemCommand("reboot", ref response);
            }, 2000);
        }
Exemple #16
0
        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);
            }
        }
Exemple #17
0
        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);
            }
        }
Exemple #18
0
        /// <summary>
        /// Reboots the control system
        /// </summary>
        public static void RebootControlSystem()
        {
            string res = "";

            CrestronConsole.SendControlSystemCommand("reboot\n", ref res);
        }
Exemple #19
0
            private void GetProgramInfo(object o)
            {
                Debug.Console(2, "Attempting to get program info for slot: {0}", Program.Number);

                string response = null;

                if (Program.RegistrationState == eProgramRegistrationState.Unregister || Program.OperatingState == eProgramOperatingState.Stop)
                {
                    Debug.Console(2, "Program {0} not registered. Setting default values for program information.",
                                  Program.Number);

                    ProgramInfo = new ProgramInfo(Program.Number)
                    {
                        OperatingState    = Program.OperatingState,
                        RegistrationState = Program.RegistrationState
                    };

                    return;
                }

                var success = CrestronConsole.SendControlSystemCommand(
                    string.Format("progcomments:{0}", Program.Number), ref response);

                if (!success)
                {
                    Debug.Console(2, "Progcomments Attempt Unsuccessful for slot: {0}", Program.Number);
                    UpdateFeedbacks();
                    return;
                }

                if (response.ToLower().Contains("bad or incomplete"))
                {
                    Debug.Console(2,
                                  "Program in slot {0} not running.  Setting default ProgramInfo for slot: {0}",
                                  Program.Number);

                    // Assume no valid program info.  Constructing a new object will wipe all properties
                    ProgramInfo = new ProgramInfo(Program.Number)
                    {
                        OperatingState    = Program.OperatingState,
                        RegistrationState = Program.RegistrationState
                    };

                    UpdateFeedbacks();

                    return;
                }


                // Shared properteis
                ProgramInfo.ProgramFile      = ParseConsoleData(response, "Program File", ": ", "\n");
                ProgramInfo.CompilerRevision = ParseConsoleData(response, "Compiler Rev", ": ", "\n");
                ProgramInfo.CompileTime      = ParseConsoleData(response, "Compiled On", ": ", "\n");
                ProgramInfo.Include4Dat      = ParseConsoleData(response, "Include4.dat", ": ", "\n");


                if (ProgramInfo.ProgramFile.Contains(".dll"))
                {
                    // SSP Program
                    ProgramInfo.FriendlyName       = ParseConsoleData(response, "Friendly Name", ": ", "\n");
                    ProgramInfo.ApplicationName    = ParseConsoleData(response, "Application Name", ": ", "\n");
                    ProgramInfo.ProgramTool        = ParseConsoleData(response, "Program Tool", ": ", "\n");
                    ProgramInfo.MinFirmwareVersion = ParseConsoleData(response, "Min Firmware Version", ": ",
                                                                      "\n");
                    ProgramInfo.PlugInVersion = ParseConsoleData(response, "PlugInVersion", ": ", "\n");
                }
                else if (ProgramInfo.ProgramFile.Contains(".smw"))
                {
                    // SIMPL Windows Program
                    ProgramInfo.FriendlyName = ParseConsoleData(response, "Friendly Name", ":", "\n");
                    ProgramInfo.SystemName   = ParseConsoleData(response, "System Name", ": ", "\n");
                    ProgramInfo.CrestronDb   = ParseConsoleData(response, "CrestronDB", ": ", "\n");
                    ProgramInfo.Environment  = ParseConsoleData(response, "Source Env", ": ", "\n");
                    ProgramInfo.Programmer   = ParseConsoleData(response, "Programmer", ": ", "\n");
                }
                Debug.Console(2, "Program info for slot {0} successfully updated", Program.Number);

                UpdateFeedbacks();
            }
Exemple #20
0
        public virtual void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            _initialized = true;

            _systemTimer = new CTimer(SystemTimerCallback, null, 1000, 1000);

            InternalClockInitialize();

            var response = string.Empty;

            CrestronConsole.SendControlSystemCommand("webport", ref response);
            var match = Regex.Match(response, @"Webserver port *= *(\d+)");

            if (match.Success)
            {
                var port = int.Parse(match.Groups[1].Value);
                Debug.WriteWarn("Built-web server is using port {0}", port);
            }

            foreach (var process in GetSystemItemsToInitialize())
            {
                _initializeQueue.Enqueue(process);
            }

            foreach (var source in Sources.Where(s => s.Device != null))
            {
                var device = source.Device as IInitializeComplete;
                if (device != null)
                {
                    _initializeQueue.Enqueue(new InitializeProcess(source.Device.Initialize,
                                                                   string.Format("Initializing Source Device: {0}", device.GetType().Name),
                                                                   TimeSpan.Zero, device.CheckInitializedOk));
                }
                else
                {
                    _initializeQueue.Enqueue(new InitializeProcess(source.Device.Initialize,
                                                                   string.Format("Initializing Source Device: {0}", source.Device.GetType().Name)));
                }
            }

            foreach (var room in Rooms)
            {
                _initializeQueue.Enqueue(new InitializeProcess(room.Initialize,
                                                               string.Format("Initializing Room: \"{0}\"", room.Name)));
            }

            var displays = Displays.Where(d => d.Device != null).ToArray();

            var count = 0;

            foreach (var display in displays)
            {
                count++;
                _initializeQueue.Enqueue(new InitializeProcess(display.Initialize,
                                                               string.Format("Initializing Display {0}", count)));
            }

            foreach (var room in Rooms.Where(r => r.FusionEnabled))
            {
                _initializeQueue.Enqueue(new InitializeProcess(room.FusionRegisterInternal,
                                                               string.Format("Registering Fusion for Room: \"{0}\"", room.Name), TimeSpan.FromSeconds(5)));
            }

            /*if (Rooms.Any(r => r.FusionEnabled))
             * {
             *  _initializeQueue.Enqueue(new InitializeProcess(FusionRVI.GenerateFileForAllFusionDevices,
             *      "Generating Fusion RVI file for discovery"));
             * }*/

            if (UIControllers.Any())
            {
                _initializeQueue.Enqueue(new InitializeProcess(UIControllers.ConnectToDefaultRooms,
                                                               "Setting up UI Controllers"));
            }

            if (UIControllers.Any())
            {
                _initializeQueue.Enqueue(new InitializeProcess(UIControllers.Initialize,
                                                               "Initializing UI Controllers"));
            }

            if (_systemThread != null)
            {
                return;
            }

            _systemThread = new Thread(SystemThreadProcess, null)
            {
                Name     = "UX.Lib2.SystemBase SystemThreadProcess()",
                Priority = Thread.eThreadPriority.LowestPriority
            };

            _systemStartupThread = new Thread(SystemStartupThreadProcess, null)
            {
                Name     = "System Startup Thread Process",
                Priority = Thread.eThreadPriority.MediumPriority
            };
        }
            /// <summary>
            /// Retrieves information about a running program
            /// </summary>
            public void GetProgramInfo()
            {
                CrestronInvoke.BeginInvoke((o) =>
                {
                    Debug.Console(2, "Attempting to get program info for slot: {0}", Program.Number);

                    string response = null;

                    var success = CrestronConsole.SendControlSystemCommand(string.Format("progcomments:{0}", Program.Number), ref response);

                    if (success)
                    {
                        //Debug.Console(2, "Progcomments Response: \r{0}", response);

                        if (!response.ToLower().Contains("bad or incomplete"))
                        {
                            // Shared properteis
                            ProgramInfo.ProgramFile      = ParseConsoleData(response, "Program File", ": ", "\n");
                            ProgramInfo.CompilerRevision = ParseConsoleData(response, "Compiler Rev", ": ", "\n");
                            ProgramInfo.CompileTime      = ParseConsoleData(response, "Compiled On", ": ", "\n");
                            ProgramInfo.Include4Dat      = ParseConsoleData(response, "Include4.dat", ": ", "\n");



                            if (ProgramInfo.ProgramFile.Contains(".dll"))
                            {
                                // SSP Program
                                ProgramInfo.FriendlyName       = ParseConsoleData(response, "Friendly Name", ": ", "\n");
                                ProgramInfo.ApplicationName    = ParseConsoleData(response, "Application Name", ": ", "\n");
                                ProgramInfo.ProgramTool        = ParseConsoleData(response, "Program Tool", ": ", "\n");
                                ProgramInfo.MinFirmwareVersion = ParseConsoleData(response, "Min Firmware Version", ": ", "\n");
                                ProgramInfo.PlugInVersion      = ParseConsoleData(response, "PlugInVersion", ": ", "\n");
                            }
                            else if (ProgramInfo.ProgramFile.Contains(".smw"))
                            {
                                // SIMPL Windows Program
                                ProgramInfo.FriendlyName = ParseConsoleData(response, "Friendly Name", ":", "\n");
                                ProgramInfo.SystemName   = ParseConsoleData(response, "System Name", ": ", "\n");
                                ProgramInfo.CrestronDB   = ParseConsoleData(response, "CrestronDB", ": ", "\n");
                                ProgramInfo.Environment  = ParseConsoleData(response, "Source Env", ": ", "\n");
                                ProgramInfo.Programmer   = ParseConsoleData(response, "Programmer", ": ", "\n");
                            }
                            //Debug.Console(2, "ProgramInfo: \r{0}", JsonConvert.SerializeObject(ProgramInfo));
                        }
                        else
                        {
                            Debug.Console(2, "Bad or incomplete console command response.  Initializing ProgramInfo for slot: {0}", Program.Number);

                            // Assume no valid program info.  Constructing a new object will wipe all properties
                            ProgramInfo = new ProgramInfo(Program.Number);

                            ProgramInfo.OperatingState    = Program.OperatingState;
                            ProgramInfo.RegistrationState = Program.RegistrationState;
                        }
                    }
                    else
                    {
                        Debug.Console(2, "Progcomments Attempt Unsuccessful for slot: {0}", Program.Number);
                    }

                    ProgramNameFeedback.FireUpdate();
                    ProgramCompileTimeFeedback.FireUpdate();
                    CrestronDataBaseVersionFeedback.FireUpdate();
                    EnvironmentVersionFeedback.FireUpdate();

                    AggregatedProgramInfoFeedback.FireUpdate();

                    OnProgramInfoChanged();
                });
            }
Exemple #22
0
        private object SystemThreadProcess(object userSpecific)
        {
            try
            {
                while (true)
                {
                    if (_userPrompts.Count == 0)
                    {
                        _systemWait.Wait(2000);
                    }

                    if (_programStopping)
                    {
                        return(null);
                    }

                    if (_userPrompts.Count == 0)
                    {
                        goto CheckTimers;
                    }

                    try
                    {
                        var prompts = _userPrompts.ToArray();

                        // We have queued prompts that aren't showing as current system prompts
                        if (prompts.Any(p => p.State == PromptState.Queued) &&
                            !prompts.Any(p => p.State == PromptState.Shown && p.Room == null))
                        {
                            //Debug.WriteInfo("Prompts queued! System {0}, Room {1}",
                            //    _userPrompts.Count(p => p.State == PromptState.Queued && p.Room == null),
                            //    _userPrompts.Count(p => p.State == PromptState.Queued && p.Room != null));

                            // Look for any system prompts (not specific to a room)
                            var prompt = prompts.FirstOrDefault(p => p.State == PromptState.Queued && p.Room == null);

                            if (prompt != null)
                            {
                                var roomPrompts = prompts.Where(p => p.State == PromptState.Shown && p.Room != null);

                                // Close any active room prompts and reset to queue as system will override

                                var pArray = roomPrompts as UserPrompt[] ?? roomPrompts.ToArray();
                                foreach (var roomPrompt in pArray)
                                {
                                    roomPrompt.State = PromptState.Queued;
                                }

                                if (pArray.Any())
                                {
                                    Thread.Sleep(200);
                                }

                                prompt.State = PromptState.Shown;

                                //Debug.WriteInfo("Showing system prompt on all UIs!");

                                foreach (var uiController in UIControllers)
                                {
                                    uiController.ShowPrompt(prompt);
                                }
                            }

                            else
                            {
                                // No system prompts to show so we can show any room prompts

                                foreach (var room in Rooms)
                                {
                                    var room1 = room;

                                    // Already showing a prompt in this room ... skip the room
                                    if (_userPrompts.Any(p => p.State == PromptState.Shown && p.Room == room1))
                                    {
                                        continue;
                                    }

                                    prompt = prompts.FirstOrDefault(
                                        p => p.State == PromptState.Queued && p.Room == room1);

                                    if (prompt != null && prompt.State != PromptState.Cancelled)
                                    {
                                        prompt.State = PromptState.Shown;

                                        foreach (var uiController in UIControllers.ForRoom(room1))
                                        {
                                            uiController.ShowPrompt(prompt);
                                        }
                                    }
                                }
                            }
                        }

                        //if (prompts.Length > 0)
                        //    Debug.WriteInfo("Removing {0} expired prompts", prompts.Length);

                        foreach (var userPrompt in
                                 prompts.Where(p => p.State != PromptState.Queued && p.State != PromptState.Shown))
                        {
                            _userPromptsLock.Enter();
                            _userPrompts.Remove(userPrompt);
                            _userPromptsLock.Leave();
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e);
                        Thread.Sleep(1000);
                    }

CheckTimers:

                    if (!Booted)
                    {
                        continue;
                    }

                    if (SecondsSinceLastSystemTimerCallback > 10 && !_timersBrokenFlag)
                    {
                        _timersBrokenFlag = true;
                        CloudLog.Error(
                            "System Timer last checked in {0} seconds ago. Will reboot processor in 10 minutes if not fixed!!",
                            SecondsSinceLastSystemTimerCallback);
                    }
                    else if (SecondsSinceLastSystemTimerCallback > 600 && _timersBrokenFlag)
                    {
                        CloudLog.Error("Automatic reboot now!");
                        var response = string.Empty;
                        CrestronConsole.SendControlSystemCommand("REBOOT", ref response);
                    }
                    else if (_timersBrokenFlag && SecondsSinceLastSystemTimerCallback < 10)
                    {
                        _timersBrokenFlag = false;
                        CloudLog.Warn("System Timer checked in {0} seconds ago after a delay", SecondsSinceLastSystemTimerCallback);
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Unhandled Exception in SystemThreadProcess()!");
                return(null);
            }
        }
        /// <summary>
        /// Gets the program info by index
        /// </summary>
        /// <param name="index"></param>
        public void GetProgramInfoByIndex(ushort index)
        {
            if (index < 1 || index > 10)
            {
                return;
            }

            OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);

            var program = new ProgramInfo();

            try
            {
                var response = "";
                CrestronConsole.SendControlSystemCommand(string.Format("progcomments:{0}", index), ref response);

                // no program loaded or running
                if (response.Contains("Bad or Incomplete Command"))
                {
                    program.Name        = "";
                    program.System      = "";
                    program.Programmer  = "";
                    program.CompileTime = "";
                    program.Database    = "";
                    program.Environment = "";
                }
                else
                {
                    // SIMPL returns
                    program.Name         = ParseConsoleResponse(response, "Program File", ":", "\x0D");
                    program.System       = ParseConsoleResponse(response, "System Name", ":", "\x0D");
                    program.ProgramIdTag = ParseConsoleResponse(response, "Friendly Name", ":", "\x0D");
                    program.Programmer   = ParseConsoleResponse(response, "Programmer", ":", "\x0D");
                    program.CompileTime  = ParseConsoleResponse(response, "Compiled On", ":", "\x0D");
                    program.Database     = ParseConsoleResponse(response, "CrestronDB", ":", "\x0D");
                    program.Environment  = ParseConsoleResponse(response, "Source Env", ":", "\x0D");

                    // S# returns
                    if (program.System.Length == 0)
                    {
                        program.System = ParseConsoleResponse(response, "Application Name", ":", "\x0D");
                    }
                    if (program.Database.Length == 0)
                    {
                        program.Database = ParseConsoleResponse(response, "PlugInVersion", ":", "\x0D");
                    }
                    if (program.Environment.Length == 0)
                    {
                        program.Environment = ParseConsoleResponse(response, "Program Tool", ":", "\x0D");
                    }
                }

                OnProgramChange(program, index, SystemInfoConstants.ProgramConfigChange);
            }
            catch (Exception e)
            {
                var msg = string.Format("GetProgramInfoByIndex failed: {0}", e.Message);
                CrestronConsole.PrintLine(msg);
                //ErrorLog.Error(msg);
            }

            OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
        }