Example #1
0
        public void Acquire()
        {
            // Fast path.

            if (Interlocked.CompareExchange(ref _value, 1, 0) == 0)
            {
                return;
            }

            // Slow path 1 - spin for a while.

            /*
             * if (SpinEnabled)
             * {
             * for (int i = 0; i < SpinCount; i++)
             * {
             * if (Interlocked.CompareExchange(ref _value, 1, 0) == 0)
             * return;
             * }
             * }
             */

            // Slow path 2 - wait on the event.

            // Note: see FastEvent.cs for a more detailed explanation of this
            // technique.

            CEvent newEvent = Interlocked.CompareExchange(ref _event, null, null);

            if (newEvent == null)
            {
                newEvent = new CEvent(true, false);

                if (Interlocked.CompareExchange(ref _event, newEvent, null) != null)
                {
                    newEvent.Close();
                }
            }

            // Loop trying to acquire the lock. Note that after we
            // get woken up another thread might have acquired the lock,
            // and that's why we need a loop.
            while (true)
            {
                if (Interlocked.CompareExchange(ref _value, 1, 0) == 0)
                {
                    break;
                }

                if (!_event.Wait(Timeout.Infinite))
                {
                    Break("Failed to wait indefinitely on an object.");
                }
            }
        }
Example #2
0
        /// <summary>
        /// Adds (or returns) an object to the pool.
        /// </summary>
        /// <param name="obj"></param>
        public void AddToPool(T obj)
        {
            if (Interlocked.Increment(ref _currentCount) > MaxCapacity)
            {
                _queueReturnEvent.Wait();
            }

            if (_disposed)
            {
                return;
            }
            _objectPool.Enqueue(obj);
            _queueAddEvent.Set();
        }
Example #3
0
        /// <summary>
        /// Aquire a lock and return the LockToken when the lock is aquired.
        /// </summary>
        /// <param name="waitTime">Amount of time to wait to aquire the lock in milliseconds</param>
        /// <returns>LockToken object</returns>
        public LockToken AquireLock(int waitTime)
        {
            var sw = Stopwatch.StartNew();

            while (sw.ElapsedMilliseconds < waitTime)
            {
                if (_criticalSection.TryEnter())
                {
                    return(new LockToken(this));
                }

                _delayEvent.Wait(100);
            }
            return(new LockToken(null));
        }
Example #4
0
 private void testEventCore(int s)
 {
     try
     {
         while (true)
         {
             myEvent.Wait();
             CrestronConsole.PrintLine("*** Event Running {0} ***", s);
         }
     }
     catch (Exception e)
     {
         CrestronConsole.PrintLine("*** Error: {0} - {1} ***", s, e.Message);
     }
 }
Example #5
0
        /// <summary>
        /// Aquire a lock and return the LockToken when the lock is aquired.
        /// </summary>
        /// <param name="waitTime">Amount of time to wait to aquire the lock in milliseconds</param>
        /// <returns>LockToken object</returns>
        public LockToken AquireLock(int waitTime)
        {
            var sw = Stopwatch.StartNew();

            while (sw.ElapsedMilliseconds < waitTime)
            {
                if (CMonitor.TryEnter(_monitorObject))
                {
                    return(new LockToken(this));
                }

                _delayEvent.Wait(100);
            }
            return(new LockToken(null));
        }
Example #6
0
        private void ReadAndBuildRxTx(object threadCallbackObject)
        {
            bool wasSet = WaitForSwitchers.Wait(5000);

            if (wasSet) // Build displays only if AV Switcher triggered event.
            {
                CrestronConsole.PrintLine("Building Tx and Rx devices...");

                //TODO create all receiver & transmitter objects that are in the configuration data.
                ReadAndBuildDisplays(threadCallbackObject);
            }
            else
            {
                ErrorLog.Warn("Tx/Rx devices and displays not configured -- AV Switcher configuration did not respond.");
            }
        }
Example #7
0
        /// <summary>
        /// Retrieves an object from the pool.
        /// </summary>
        /// <returns>Pool object.</returns>
        public T GetFromPool()
        {
            if (_currentCount == 0)
            {
                _queueAddEvent.Wait();
            }

            if (_disposed)
            {
                return(null);
            }
            Interlocked.Decrement(ref _currentCount);
            var obj = _objectPool.Dequeue();

            _queueReturnEvent.Set();
            return(obj);
        }
Example #8
0
        private static object UploadProcess(object userSpecific)
        {
            Notice("CloudLog UploadProcess Started");

            while (true)
            {
                CrestronEnvironment.AllowOtherAppsToRun();

                if (_linkDown && !_programEnding)
                {
                    Thread.Sleep(60000);
                }
                else if (!_linkDown)
                {
                    try
                    {
                        var entries = PendingLogs.Take(50);

                        try
                        {
#if DEBUG
                            //CrestronConsole.PrintLine("Updating autodiscovery query...");
#endif
                            var query = EthernetAutodiscovery.Query();

#if DEBUG
                            //CrestronConsole.PrintLine("Autodiscovery {0}", query);
#endif
                            if (query ==
                                EthernetAutodiscovery.eAutoDiscoveryErrors.AutoDiscoveryOperationSuccess)
                            {
                                var adresults = EthernetAutodiscovery.DiscoveredElementsList;
#if DEBUG
                                //CrestronConsole.PrintLine("Found {0} devivces:", adresults.Count);
#endif
                                foreach (var adresult in adresults)
                                {
                                    //CrestronConsole.PrintLine("{0}, {1}, {2}", adresult.IPAddress,
                                    //adresult.HostName, adresult.DeviceIdString);
                                }
                            }
#if DEBUG
                            //CrestronConsole.PrintLine("CloudLog uploading to cloud...");
#endif

                            var contents = Post("submit_logs", entries);
                            var data     = JObject.Parse(contents);
#if DEBUG
                            //CrestronConsole.PrintLine("CloudLog client response: {0}", data["status"].Value<string>());
#endif
                            var results = data["results"];
                            foreach (var id in results.Select(result => result["id"].Value <string>()))
                            {
                                InternalDictionary[id].CloudId = id;
                            }
                        }
                        catch (Exception e)
                        {
                            Error("Error with CloudLog upload process, {0}", e.Message);
                            if (_programEnding)
                            {
                                return(null);
                            }
                            CrestronConsole.PrintLine("CloudLog could not upload to cloud service. {0} items pending",
                                                      PendingLogs.Count);
                            Thread.Sleep(60000);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorLog.Error("Error in CloudLog.PostToCloudProcess, {1}", e.Message);
                    }
                }

                if (_programEnding)
                {
                    return(null);
                }

                if (PendingLogs.Count == 0)
                {
                    UploadEvent.Wait(60000);
                }
            }
        }
 /// <summary>
 /// Waits indefinitely to be signaled.
 /// </summary>
 /// <returns>True if signaled, otherwise false.</returns>
 /// <remarks>Automatically resets the state of the signal.</remarks>
 public bool Wait()
 {
     return(_cEvent.Wait());
 }
Example #10
0
        public void ConnectionStart()
        {
            if (_connectionId > 0 || (_connectionThread != null && _connectionThread.ThreadState == Thread.eThreadStates.ThreadRunning))
            {
                return;
            }
            _connectionActive = true;
            _connectionWait.Reset();
            CloudLog.Notice("{0} Initialize() called", GetType().Name);
            _connectionThread = new Thread(specific =>
            {
                while (_connectionActive && !_programStopping)
                {
                    var suppressErrors = false;

                    UriBuilder uri;
                    Task <HttpResponseMessage> task;
                    HttpResponseMessage response;
                    Task <string> readTask;
                    string content;
                    JToken json;

                    while (_connectionId == 0)
                    {
                        try
                        {
                            uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                            {
                                Query = "action=connect"
                            };

                            Debug.WriteInfo("Trying to connect to " + uri.Uri);

                            task     = _client.GetAsync(uri.Uri);
                            response = task.Await();

                            response.EnsureSuccessStatusCode();

                            readTask = response.Content.ReadAsStringAsync();
                            content  = readTask.Await();
#if DEBUG
                            Debug.WriteInfo("Response content:\r\n" + content);
#endif
                            json = JToken.Parse(content);

                            _connectionId = int.Parse(json["connectionid"].Value <string>());
                            CloudLog.Debug("{0} connected and received conenction id of \"{1}\"", GetType().Name,
                                           _connectionId);

                            try
                            {
                                var eventInfo   = json["configevents"].First;
                                _currentClip    = eventInfo["eParamID_CurrentClip"].Value <string>();
                                _transportState =
                                    (ETransportState)int.Parse(eventInfo["eParamID_TransportState"].Value <string>());
                                OnTransportModeChanged(this);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteWarn("Could not parse configevents on connect, {0}", e.Message);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!suppressErrors)
                            {
                                suppressErrors = true;
                                CloudLog.Error("Error trying to connect to {0}, {1}", GetType().Name, e.Message);
                                CloudLog.Warn("{0} will try again in 5 seconds", GetType().Name);
                            }

                            _connectionWait.Wait(5000);

                            DeviceCommunicating = false;
                        }
                    }

                    DeviceCommunicating = true;

                    uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                    {
                        Query = "action=get&paramid=eParamID_TransportState"
                    };

                    Debug.WriteInfo("Trying to connect to " + uri.Uri);

                    task     = _client.GetAsync(uri.Uri);
                    response = task.Await();

                    response.EnsureSuccessStatusCode();
                    readTask = response.Content.ReadAsStringAsync();
                    content  = readTask.Await();
#if DEBUG
                    Debug.WriteWarn("Response content:\r\n" + content);
#endif
                    json = JToken.Parse(content);

                    TransportState = (ETransportState)int.Parse(json["value"].Value <string>());

                    while (_connectionActive)
                    {
                        var timeStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                        uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                        {
                            Query =
                                string.Format("action=wait_for_config_events&connectionid={0}&_={1}", _connectionId,
                                              timeStamp)
                        };

                        Debug.WriteInfo("Trying to connect to " + uri.Uri);

                        task     = _client.GetAsync(uri.Uri);
                        response = task.Await();

                        if (response.StatusCode == HttpStatusCode.Gone)
                        {
                            _connectionId = 0;
                            break;
                        }

                        response.EnsureSuccessStatusCode();
                        readTask = response.Content.ReadAsStringAsync();
                        content  = readTask.Await();
#if DEBUG
                        Debug.WriteWarn("Response content:\r\n" + content);
#endif
                        json = JToken.Parse(content);

                        foreach (var item in json)
                        {
                            var paramId = item["param_id"].Value <string>();
                            switch (paramId)
                            {
                            case "eParamID_DisplayTimecode":
                                _timeCode = item["str_value"].Value <string>();
                                break;

                            case "eParamID_CurrentClip":
                                _currentClip = item["str_value"].Value <string>();
                                break;

                            case "eParamID_TransportState":
                                _transportState = (ETransportState)item["int_value"].Value <int>();
                                break;
                            }
                        }

                        OnTransportModeChanged(this);

                        CrestronEnvironment.AllowOtherAppsToRun();

                        _connectionWait.Wait(100);
                    }
                }

                _connectionId = 0;

                return(null);
            }, null);
        }
Example #11
0
        private object CheckStatusThread(object userSpecific)
        {
            CloudLog.Info("{0} Started status checking thread", GetType().Name);

            while (!_programStopping)
            {
                try
                {
                    if (_inputStatusNotChecked)
                    {
                        _checkWait.Wait(5000);
                    }
                    else
                    {
                        _checkWait.Wait(60000);
                    }

                    _threadRunning = true;

                    CrestronEnvironment.AllowOtherAppsToRun();
                    Thread.Sleep(0);

                    if (_programStopping)
                    {
                        return(null);
                    }

                    #region Get System Info

                    var response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/system", "getSystemInformation", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        if (response.ConnectionFailed)
                        {
                            DeviceCommunicating = false;
                            _connectionOk       = false;
                        }
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JObject;
                        _serialNumber = info["serial"].Value <string>();
                        _model        = info["model"].Value <string>();
                        _macAddress   = info["macAddr"].Value <string>();
                        _versionInfo  = info["generation"].Value <string>();
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                    }

                    #endregion

                    #region Get Power Status

                    var previousPowerWasNotOn = PowerStatus != DevicePowerStatus.PowerOn;

                    response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/system", "getPowerStatus", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        if (response.ConnectionFailed)
                        {
                            DeviceCommunicating = false;
                            _connectionOk       = false;
                        }
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JObject;

                        switch (info["status"].Value <string>())
                        {
                        case "standby":
                            SetPowerFeedback(DevicePowerStatus.PowerOff);
                            break;

                        case "active":
                            SetPowerFeedback(DevicePowerStatus.PowerOn);
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                        continue;
                    }

                    #endregion

                    DeviceCommunicating = true;

                    if (PowerStatus == DevicePowerStatus.PowerOn)
                    {
                        #region Get Input Status

                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent",
                                                         "getPlayingContentInfo", "1.0").Await();
                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("Error trying to get input status from Sony Display, will try again in 5 seconds");
                            _inputStatusNotChecked = true;
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JObject;

                            var uri = info["uri"].Value <string>();

                            if (_availableSources != null && _availableSources.Any(s => s != null && s.Uri == uri))
                            {
                                _currentInput = _availableSources.First(s => s.Uri == uri).InputType;

                                if (_requestedInput != DisplayDeviceInput.Unknown && _currentInput != _requestedInput)
                                {
                                    SetInput(_requestedInput,
                                             previousPowerWasNotOn ? TimeSpan.FromSeconds(2) : TimeSpan.Zero);
                                }
                                else if (_requestedInput == _currentInput)
                                {
                                    _requestedInput = DisplayDeviceInput.Unknown;
                                }
                            }
                            else
                            {
                                _currentInput = DisplayDeviceInput.Unknown;
                            }

                            _inputStatusNotChecked = false;
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }

                        #endregion

                        #region Get Volume Level

                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/audio", "getVolumeInformation",
                                                         "1.0").Await();
                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            continue;
                        }

                        try
                        {
                            foreach (var token in response.Data.First())
                            {
                                var info = token as JObject;

                                var type =
                                    (TargetVolumeDeviceType)
                                    Enum.Parse(typeof(TargetVolumeDeviceType), info["target"].Value <string>(), true);

                                var currentLevel = info["volume"].Value <int>();
                                var minLevel     = info["minVolume"].Value <int>();
                                var maxLevel     = info["maxVolume"].Value <int>();
                                var mute         = info["mute"].Value <bool>();

                                var control =
                                    _volumeControls.Cast <SonyBraviaVolumeControl>()
                                    .FirstOrDefault(c => c.TargetType == type);

                                if (control == null)
                                {
                                    continue;
                                }

                                control.VolumeMin     = minLevel;
                                control.VolumeMax     = maxLevel;
                                control.InternalLevel = currentLevel;
                                control.InternalMute  = mute;
                            }
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }

                        #endregion
                    }

                    if (_connectionOk)
                    {
                        continue;
                    }

                    CloudLog.Info("{0} at {1} will now get status. Either failed previously or first connect",
                                  GetType().Name, DeviceAddressString);

                    #region Get Input and Source Schemes

                    var schemes = new List <string>();

                    response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getSchemeList", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        CloudLog.Error("{0} could not get SchemeList, {1}", GetType().Name, response.Type);
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JArray;

                        schemes.AddRange(info.Select(token => token as JObject).Select(o => o["scheme"].Value <string>()));

                        if (schemes.Count == 0)
                        {
                            CloudLog.Warn("Received empty array for {0} getSchemeList, moving to generate defaults",
                                          GetType().Name);
                            goto ErrorGettingInputs;
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                        continue;
                    }

                    var sources = new Dictionary <string, List <string> >();

                    foreach (var scheme in schemes)
                    {
                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getSourceList", "1.0",
                                                         new JObject
                        {
                            { "scheme", scheme }
                        }).Await();

                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("{0} could not get SourceList for scheme \"{1}\", {2}",
                                          GetType().Name, scheme, response.Type);
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JArray;

                            var list = new List <string>();
                            sources[scheme] = list;
                            list.AddRange(info.Select(token => token as JObject)
                                          .Select(o => o["source"].Value <string>()));
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }
                    }

                    var newContentList = new List <SonyContentSource>();

                    foreach (
                        var source in
                        sources.Where(k => k.Key != "fav").Select(k => k.Value).SelectMany(scheme => scheme))
                    {
                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getContentList",
                                                         "1.0", new JObject
                        {
                            { "source", source }
                        }).Await();

                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("{0} could not get ConntentList for source \"{1}\", {2}",
                                          GetType().Name, source, response.Type);
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JArray;

                            foreach (var token in info)
                            {
                                try
                                {
                                    var input = new SonyContentSource(token as JObject);
                                    newContentList.Add(input);
                                    Debug.WriteInfo("Sony content source", input.ToString());
                                }
                                catch (Exception e)
                                {
                                    CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                                       response.RequestMethod);
                                }
                            }

                            goto FoundInputs;
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }
                    }

ErrorGettingInputs:
                    CloudLog.Warn("Error getting input schemes for {0}, Generating default HDMI inputs", GetType().Name);
                    _availableSources = new List <SonyContentSource>()
                    {
                        new SonyContentSource("extInput:hdmi?port=1", "HDMI 1", 0),
                        new SonyContentSource("extInput:hdmi?port=2", "HDMI 2", 1),
                        new SonyContentSource("extInput:hdmi?port=3", "HDMI 3", 2),
                        new SonyContentSource("extInput:hdmi?port=4", "HDMI 4", 3)
                    };
                    goto InputsDone;

FoundInputs:
                    _availableSources = newContentList;

InputsDone:
                    Debug.WriteSuccess("Available inputs");
                    foreach (var source in _availableSources)
                    {
                        Debug.WriteNormal(source.ToString());
                    }

                    #endregion

                    _connectionOk = true;
                }
                catch (Exception e)
                {
                    CloudLog.Error("Error in {0}, message = {1}", Thread.CurrentThread.Name, e.Message);
                }
            }

            return(null);
        }
        /// <summary>
        ///     Waits for the event to be set.
        /// </summary>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait.</param>
        /// <returns>Whether the event was set before the timeout period elapsed.</returns>
        public bool Wait(int millisecondsTimeout)
        {
            // 1. [Optional] If Value = 1, Return.
            // 2. [Optional] If Timeout = 0 And Value = 0, Return.
            // 3. [Optional] Reference the Global Event.
            // 4. [Optional] If Global Event is present, skip Step 5.
            // 5. Create Event.
            // 6. Global Event = Event only if Global Event is not present.
            // 7. If Value = 1, Return (rather, go to Step 9).
            // 8. Wait for Global Event.
            // 9. [Optional] Dereference the Global Event.


            int result = _autoReset ? InterlockedEx.And(ref _value, ~EventSet) : _value;

            // Shortcut: return immediately if the event is set.
            if ((result & EventSet) != 0)
            {
                return(true);
            }

            // Shortcut: if the timeout is 0, return immediately if
            // the event isn't set.
            if (millisecondsTimeout == 0)
            {
                return(false);
            }

            // Prevent the event from being closed or invalidated.
            RefEvent();

            // Shortcut: don't bother creating an event if we already have one.
            CEvent newEvent = _event;

            // If we don't have an event, create one and try to set it.
            if (newEvent == null)
            {
                // Create an event. We might not need it, though.
                newEvent = new CEvent(_autoReset, false);

                // Atomically use the event only if we don't already
                // have one.
                if (Interlocked.CompareExchange(ref _event, newEvent, null) != null)
                {
                    // Someone else set the event before we did.
                    newEvent.Close();
                }
            }

            try
            {
                // Check the value to see if we are meant to wait. This step
                // is essential, because if someone set the event before we
                // created the event (previous step), we would be waiting
                // on an event no one knows about.
                if ((_value & EventSet) != 0)
                {
                    return(true);
                }

                return(_event.Wait(millisecondsTimeout));
            }
            finally
            {
                // We don't need the event anymore.
                DerefEvent();
            }
        }
Example #13
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 #14
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);
        }
        private object UpdateFeedbackProcess(object userSpecific)
        {
            CloudLog.Notice("Started " + Thread.CurrentThread.Name);

            var feedback = true;

            var itemStates = new Dictionary <RoutingListItem, ItemState>();

            while (RequestedVisibleState && !_programStopping && _switcher.Chassis.IsOnline)
            {
                if (_selectedInput != null)
                {
                    _routedOutputsForSelectedInput = new List <DMOutput>();
                    foreach (
                        var output in
                        _switcher.Chassis.Outputs.Values.Where(
                            o => o.VideoOutFeedback != null && o.VideoOutFeedback == _selectedInput))
                    {
                        _routedOutputsForSelectedInput.Add(output);
                    }

                    foreach (var item in _outputList.Cast <RoutingListItem>().TakeWhile(item => item.LinkedObject != null))
                    {
                        var output        = (DMOutput)item.LinkedObject;
                        var alreadyRouted = _routedOutputsForSelectedInput.Contains(output);
                        var willChange    = _outputsToChange.Keys.Contains(output);

                        itemStates[item] = new ItemState {
                            Color = RoutingItemListColor.Blue, Feedback = false
                        };

                        if (alreadyRouted && willChange)
                        {
                            itemStates[item].Color    = RoutingItemListColor.Red;
                            itemStates[item].Feedback = feedback;
                        }
                        else if (willChange && _outputsToChange[output] == _selectedInput)
                        {
                            itemStates[item].Color    = RoutingItemListColor.Green;
                            itemStates[item].Feedback = feedback;
                        }
                        else if (alreadyRouted)
                        {
                            itemStates[item].Feedback = true;
                        }
                    }
                }
                else
                {
                    foreach (var item in _outputList.Cast <RoutingListItem>().TakeWhile(item => item.LinkedObject != null))
                    {
                        itemStates[item] = new ItemState {
                            Color = RoutingItemListColor.Blue, Feedback = false
                        };
                    }
                }

                foreach (var itemState in itemStates)
                {
                    itemState.Key.Feedback = itemState.Value.Feedback;
                    itemState.Key.Color    = itemState.Value.Color;
                }

                _cancelButton.Enabled = _outputsToChange.Count > 0 || _selectedInput != null;
                _takeButton.Enabled   = _outputsToChange.Count > 0;

                if (_updateFeedbackEvent.Wait(500))
                {
                    feedback = true;
                }
                else
                {
                    feedback = !feedback;
                }
            }

            if (RequestedVisibleState)
            {
                Debug.WriteInfo("Showing DM offline prompt on " + UIController.ToString());
                ((BaseUIController)UIController).ActionSheetDefault.Show((type, args) => { }, "Switcher Offline",
                                                                         "The DM Switcher is offline", "OK");
            }

            CloudLog.Notice("Exiting " + Thread.CurrentThread.Name);

            return(null);
        }
 protected override bool WaitOneInternal(int timeout)
 {
     return(ce.Wait(timeout));
 }