Example #1
0
        public override IEnumerable <IDevice> GetSystemDevices()
        {
            var devices = Sources
                          .Select(source => source.Device as IDevice)
                          .Where(sourceDevice => sourceDevice != null).ToList();

            devices.AddRange(UIControllers.Cast <IDevice>());

            if (Dsp != null)
            {
                devices.Add(Dsp);
            }

            devices.AddRange(
                (from room in Rooms.Where(r => r is ARoom).Cast <ARoom>()
                 where room.IoFrameDevice != null
                 select room.IoFrameDevice).Cast <IDevice>());

            devices.AddRange(Displays.Where(d => d.Device != null)
                             .Select(display => display.Device)
                             .Cast <IDevice>());

            if (Codecs != null)
            {
                foreach (var codec in Codecs.Values.Where(codec => !devices.Contains(codec)))
                {
                    devices.Add(codec);
                }
            }

            if (Switcher != null)
            {
                devices.Add(Switcher);
            }

            return(devices);
        }
Example #2
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);
            }
        }
Example #3
0
        private object SystemStartupThreadProcess(object userSpecific)
        {
            var startingCount = _initializeQueue.Count + 1;

            var timeout = 30;

            while (UIControllers.Any(ui => !ui.Device.IsOnline && !(ui.Device is XpanelForSmartGraphics)))
            {
                if (!_programStopping || timeout == 0)
                {
                    break;
                }
                OnSystemStartupProgressChange("Waiting for devices to connect",
                                              (ushort)Tools.ScaleRange(1, 0, startingCount, ushort.MinValue,
                                                                       ushort.MaxValue), false);
                _startupWait.Wait(1000);
                timeout--;
            }

            if (_programStopping)
            {
                return(null);
            }

            while (!_initializeQueue.IsEmpty && !_programStopping)
            {
                var process = _initializeQueue.Dequeue();

                var progress = startingCount - _initializeQueue.Count;
                OnSystemStartupProgressChange(process.ProcessDescription,
                                              (ushort)
                                              Tools.ScaleRange(progress, 0, startingCount, ushort.MinValue,
                                                               ushort.MaxValue), false);
                _startupWait.Wait((int)process.TimeToWaitBeforeRunningProcess.TotalMilliseconds);
                try
                {
                    process.InitializeDelegate();
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error calling InitializeDelegate: \"{0}\"", process.ProcessDescription);
                }

                if (process.CheckCompleteCallback != null)
                {
                    var count = 0;
                    while (!process.CheckCompleteCallback() && count < 300)
                    {
                        count++;
                        _startupWait.Wait(1000);
                    }
                }
                else
                {
                    _startupWait.Wait(500);
                }
            }

            if (_programStopping)
            {
                return(null);
            }

            Booted = true;
            OnSystemStartupProgressChange("Booted OK", ushort.MaxValue, true);
            foreach (var uiController in UIControllers)
            {
                uiController.ShowMainView();
            }

            foreach (var room in Rooms)
            {
                room.CheckFusionAssetsForOnlineStatusAndReportErrors();
            }

            return(null);
        }
Example #4
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
            };
        }
Example #5
0
        protected ASystem(CrestronControlSystem controlSystem)
            : base(controlSystem, Assembly.GetExecutingAssembly())
        {
            Debug.WriteInfo("System.ctor()", "Started");

            BootStatus          = "Loading System Type \"" + GetType().Name + "\"";
            BootProgressPercent = 5;

            SoftwareUpdate.SoftwareUpdate.UpdateShouldLoad += LoadUpdate;

            CrestronConsole.AddNewConsoleCommand(parameters =>
            {
                if (parameters.Trim() == "?")
                {
                    CrestronConsole.ConsoleCommandResponse(
                        "Start running a test script. Options here are as follows:\r\n" +
                        "  count  - set the number of times the script should loop and change sources\r\n" +
                        "  number - set the number to dial if the codec is selected\r\n" +
                        "for example: \"TestScriptStart count 10 number 1234");
                    return;
                }

                var args = new Dictionary <string, string>();

                try
                {
                    var matches = Regex.Matches(parameters, @"(?:(\w+)\s+(\w+))");

                    foreach (Match match in matches)
                    {
                        args[match.Groups[1].Value] = match.Groups[2].Value;
                    }
                }
                catch (Exception e)
                {
                    CrestronConsole.ConsoleCommandResponse("Error parsing args, {0}", e.Message);
                    return;
                }

                try
                {
                    TestScriptStart(args);
                }
                catch (Exception e)
                {
                    CrestronConsole.ConsoleCommandResponse("Error: {0}", e.Message);
                }
            }, "TestScriptStart", "Start a test script", ConsoleAccessLevelEnum.AccessOperator);

            CrestronConsole.AddNewConsoleCommand(parameters => TestScriptStop(), "TestScriptStop",
                                                 "Stop running the test script", ConsoleAccessLevelEnum.AccessOperator);

            CrestronConsole.AddNewConsoleCommand(parameters =>
            {
                try
                {
                    var id          = uint.Parse(parameters);
                    Rooms[1].Source = id == 0 ? null : Sources[id];
                    CrestronConsole.ConsoleCommandResponse("Selected source \"{0}\" in Room \"{1}\"", Sources[id],
                                                           Rooms[1].Name);
                }
                catch (Exception e)
                {
                    CrestronConsole.ConsoleCommandResponse("Error: {0}", e.Message);
                }
            }, "Source", "Select a source by ID for the first room", ConsoleAccessLevelEnum.AccessOperator);

            CrestronConsole.AddNewConsoleCommand(parameters =>
            {
                try
                {
                    foreach (var source in Sources)
                    {
                        CrestronConsole.ConsoleCommandResponse("Source {0}: {1}", source.Id, source.Name);
                    }
                }
                catch (Exception e)
                {
                    CrestronConsole.ConsoleCommandResponse("Error: {0}", e.Message);
                }
            }, "ListSources", "List sources by IDs", ConsoleAccessLevelEnum.AccessOperator);

            StartWebApp(9001);

            if (ConfigManager.Config.SystemType == SystemType.NotConfigured)
            {
                return;
            }

            var config = ConfigManager.Config;

            Debug.WriteInfo("System.ctor()", "Config loaded");

            #region System Switcher

            BootStatus          = "Loading switcher configuration";
            BootProgressPercent = 6;

            if (config.SwitcherType != SystemSwitcherType.NotInstalled)
            {
                try
                {
                    switch (config.SwitcherType)
                    {
                    case SystemSwitcherType.BigDmFrame:
                        Switcher = new BigDmSwitcher(controlSystem as ControlSystem,
                                                     config.SwitcherConfig);
                        Switcher.InputStatusChanged += LocalSwitcherOnInputStatusChanged;
                        break;

                    case SystemSwitcherType.DmFrame:
                        Switcher = new DmSwitcher(controlSystem as ControlSystem,
                                                  config.SwitcherConfig);
                        Switcher.InputStatusChanged += LocalSwitcherOnInputStatusChanged;
                        break;
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error loading System Video Switcher");
                }
            }

            #endregion

            var controllers = config.OneBeyondAddresses.ToDictionary(address => address.Key,
                                                                     address => new OneBeyond(address.Value, address.Key));

            _oneBeyondControllers = new ReadOnlyDictionary <uint, OneBeyond>(controllers);

            #region DSP

            BootStatus          = "Loading dsp configuration";
            BootProgressPercent = 7;

            if (config.DspConfig != null && config.DspConfig.Enabled)
            {
                Dsp = new QsysCore(new[] { config.DspConfig.DeviceAddressString }, config.DspConfig.Name,
                                   config.DspConfig.Username, config.DspConfig.Password);
                Dsp.HasIntitialized += DspOnHasIntitialized;
            }

            #endregion

            #region Rooms

            BootStatus          = "Loading Room Configs";
            BootProgressPercent = 10;

            foreach (var roomConfig in config.Rooms
                     .Where(r => r.Enabled)
                     .OrderBy(r => r.Id))
            {
                Debug.WriteInfo("System.ctor()", "Setting up {0} room \"{1}\"", config.SystemType, roomConfig.Name);
                try
                {
                    var room = (ARoom)Assembly.GetExecutingAssembly()
                               .GetType(roomConfig.RoomType)
                               .GetConstructor(new CType[] { GetType(), typeof(RoomConfig) })
                               .Invoke(new object[] { this, roomConfig });
                    WebApp.AddXpanelLink(string.Format("/dashboard/app/xpanel/xpanel?room={0}", room.Id), room.Name);
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Failed to load room type \"{0}\"", roomConfig.RoomType);
                }
            }

            #endregion

            #region Global Sources

            if (config.GlobalSources != null)
            {
                foreach (var sourceConfig in config.GlobalSources
                         .Where(s => s.Enabled)
                         .OrderBy(s => s.Id))
                {
                    Debug.WriteInfo("System.ctor()", "Setting up global source \"{0}\", {1}", sourceConfig.Name,
                                    sourceConfig.SourceType);

                    switch (sourceConfig.SourceType)
                    {
                    case SourceType.AppleTV:
                        var appleTV = new AppleTV(controlSystem.IROutputPorts[sourceConfig.DeviceAddressNumber]);
                        new GenericSource(this, sourceConfig, appleTV);
                        break;

                    case SourceType.PC:
                        new PCSource(this, sourceConfig);
                        break;

                    default:
                        new GenericSource(this, sourceConfig);
                        break;
                    }
                }
            }

            #endregion

            #region User Interfaces

            BootStatus          = "Loading UI Controllers";
            BootProgressPercent = 15;
#if DEBUG
            Debug.WriteInfo("Setting up User Interfaces", "Count = {0}", config.UserInterfaces.Count(ui => ui.Enabled));
            Debug.WriteInfo(JToken.FromObject(config.UserInterfaces).ToString(Formatting.Indented));
#endif

            foreach (var uiConfig in config.UserInterfaces.Where(ui => ui.Enabled))
            {
                try
                {
                    Debug.WriteInfo("System.ctor()", "Setting up UIController \"{0}\", {1} 0x{2:X2}", uiConfig.Name,
                                    uiConfig.DeviceType, uiConfig.DeviceAddressNumber);

                    if (uiConfig.UIControllerType == UIControllerType.RemoteMpc)
                    {
                        var isc = new ThreeSeriesTcpIpEthernetIntersystemCommunications(uiConfig.DeviceAddressNumber,
                                                                                        uiConfig.DeviceAddressString, controlSystem);
                        var mpcUi = new MpcUIController(this, isc, Rooms.ContainsKey(uiConfig.DefaultRoom)
                            ? Rooms[uiConfig.DefaultRoom]
                            : null);
                        mpcUi.Register();
                        continue;
                    }

                    var uiAssembly = Assembly.LoadFrom(@"Crestron.SimplSharpPro.UI.dll");
                    var type       = uiAssembly.GetType("Crestron.SimplSharpPro.UI." + uiConfig.DeviceType);
                    BasicTriListWithSmartObject panel;
                    var ctor = type.GetConstructor(new CType[] { typeof(UInt32), typeof(ControlSystem) });
                    panel = (BasicTriListWithSmartObject)
                            ctor.Invoke(new object[] { uiConfig.DeviceAddressNumber, controlSystem });

                    var app = panel as CrestronApp;
                    if (app != null && !string.IsNullOrEmpty(uiConfig.DeviceAddressString))
                    {
                        app.ParameterProjectName.Value = uiConfig.DeviceAddressString;
                    }

                    if (panel != null)
                    {
                        panel.Description = uiConfig.Name;
                    }

                    UIController ui = null;

                    RoomBase defaultRoom;
                    switch (uiConfig.UIControllerType)
                    {
                    case UIControllerType.TechPanel:
                        defaultRoom = Rooms.ContainsKey(uiConfig.DefaultRoom)
                                ? Rooms[uiConfig.DefaultRoom]
                                : null;
                        ui = new RoomUIController(this, panel, defaultRoom, true);
                        break;

                    case UIControllerType.UserPanel:
                        defaultRoom = Rooms.ContainsKey(uiConfig.DefaultRoom)
                                ? Rooms[uiConfig.DefaultRoom]
                                : null;
                        ui = new RoomUIController(this, panel, defaultRoom, false);
                        break;
                    }

                    foreach (var room in uiConfig.AllowedRoomIds)
                    {
                        ui.AddRoomToAllowedRooms(Rooms[room]);
                    }

                    if (ui != null)
                    {
                        ui.Register();
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error loading UI device {0} 0x{1:X2}", uiConfig.DeviceType,
                                       uiConfig.DeviceAddressNumber);
                }
            }

            UIControllers.SetupCustomTime(Serials.Time);
            UIControllers.SetupCustomDate(Serials.Date);

            #endregion

            if (this is FireAlarmMonitorSystem)
            {
                return;
            }

            var fireInterfaceAddress = ConfigManager.GetCustomValue("FireAlarmInterfaceAddress") as string;
            if (string.IsNullOrEmpty(fireInterfaceAddress))
            {
                return;
            }
            _fireAlarmListener = new FireAlarmListener(fireInterfaceAddress);
            _fireAlarmListener.StatusChanged += FireAlarmListenerOnStatusChanged;
        }