示例#1
0
        private void AssetCommsAlertTimerProcess(object userSpecific)
        {
            var itemsToRemove = new List <FusionStaticAsset>();

            foreach (var kvp in _assetCommsStatus)
            {
                var asset = kvp.Key;
                var info  = kvp.Value;

                if (!info.ShouldRaiseAlert)
                {
                    continue;
                }

                if (info.Communicating)
                {
                    CloudLog.Info("Notifying Fusion asset \"{0}\" is back online", asset.ParamAssetName);
                }
                else
                {
                    CloudLog.Warn("Notifying Fusion asset \"{0}\" is now offline", asset.ParamAssetName);
                }

                itemsToRemove.Add(asset);
                asset.Connected.InputSig.BoolValue    = info.Communicating;
                asset.AssetError.InputSig.StringValue = !info.Communicating ? "3:Device is offline" : "0:Device is online";
            }

            foreach (var assetKey in itemsToRemove)
            {
                _assetCommsStatus.Remove(assetKey);
            }
        }
示例#2
0
        protected virtual void DspOnHasIntitialized(QsysCore core)
        {
            CloudLog.Notice(string.Format("Q-Sys Core: \"{0}\" Has Intitialized!", core.Name));
            foreach (var component in core)
            {
                foreach (var control in component)
                {
                    CloudLog.Info("Core Control: {0}", control.ToString());
                }
            }

            foreach (var itemConfig in ConfigManager.Config.DspFaderComponents.Where(c => !string.IsNullOrEmpty(c.TrafficLightBaseName)))
            {
                try
                {
                    core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".signal"]);
                    core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".good"]);
                    core.GetChangeGroup("TrafficLights").Add(core[itemConfig.TrafficLightBaseName + ".peak"]);
                }
                catch
                {
                }
            }

            core.GetChangeGroup("TrafficLights").PollAuto(0.2);
        }
示例#3
0
        /// <summary>
        /// Create a CodecSshClient
        /// </summary>
        internal CiscoSshClient(string address, int port, string username, string password)
        {
            _address  = address;
            _port     = port;
            _username = username;
            _password = password;
            CrestronEnvironment.ProgramStatusEventHandler += type =>
            {
                _programRunning = type != eProgramStatusEventType.Stopping;
                if (_programRunning)
                {
                    return;
                }

                _threadWait.Set();
                _reconnect = false;

                if (!Connected)
                {
                    return;
                }

                CloudLog.Info("Program stopping, Sending bye to {0} at {1}", GetType().Name, _address);
                Send("bye");
            };
            _heartbeatId =
                CrestronEthernetHelper.GetEthernetParameter(
                    CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter));
        }
示例#4
0
        internal void QueueRequest(ServerRequest request)
        {
            RequestQueue.Enqueue(request);

            if (_dispatchThread != null && _dispatchThread.ThreadState == Thread.eThreadStates.ThreadRunning)
            {
                return;
            }

            _dispatchThread = new Thread(specific =>
            {
#if true
                Debug.WriteSuccess("AvediaServer", "Launching {0}.DispacthThread, Request Count = {1}", GetType().Name,
                                   RequestQueue.Count);
                Debug.WriteInfo("AvediaServer", "HttpClient Timeout = {0}, TimeoutEnabled = {1}", HttpClient.Timeout,
                                HttpClient.TimeoutEnabled);
#endif

                while (true)
                {
                    var r = RequestQueue.Dequeue();
                    if (request == null)
                    {
                        CloudLog.Info("Exiting {0}", Thread.CurrentThread.Name);
                        return(null);
                    }
#if true
                    CrestronConsole.PrintLine("{0} {1}", r.RequestType.ToString(), r.Url);
                    if (r.RequestType == RequestType.Post)
                    {
                        CrestronConsole.PrintLine(r.ContentString);
                    }
#endif
                    try
                    {
                        var response = HttpClient.Dispatch(r);

                        try
                        {
                            r.Callback(response, HTTP_CALLBACK_ERROR.COMPLETED);
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e);
                        }
                    }
                    catch
                    {
                        r.Callback(null, HTTP_CALLBACK_ERROR.UNKNOWN_ERROR);
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                }
            }, null)
            {
                Name = "Avedia HTTP dispatch process"
            };
        }
        protected BaseUIController(SystemBase system, BasicTriListWithSmartObject device, RoomBase room)
            : base(system, device, room)
        {
            try
            {
                var assembly   = Assembly.GetExecutingAssembly();
                var streamName =
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(n => n.Contains(".sgd") && n.Contains(device.Name)) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(
                        n => n.Contains(".sgd") && n.Contains("XPanel") && device is XpanelForSmartGraphics) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(
                        n => n.Contains(".sgd") && n.Contains("CrestronApp") && device is CrestronApp) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(n => n.Contains(".sgd"));
                CloudLog.Info("Loading Smartgraphics for {0} ID {1}, File: {2}", GetType().Name, Id, streamName);
                var stream = assembly.GetManifestResourceStream(streamName);
                LoadSmartObjects(stream);
            }
            catch
            {
                CloudLog.Error("Could not load SGD file for {0}", this);
            }

            _roomNameLabel          = new UILabel(this, Serials.RoomName);
            _roomContactNumberLabel = new UILabel(this, Serials.RoomContactNumber);

            _bootPage = new BootPageViewController(this, Digitals.PageBoot, null);

            var tswX60BaseClass = device as TswX60BaseClass;

            if (tswX60BaseClass != null)
            {
                tswX60BaseClass.ExtenderSystem2ReservedSigs.Use();
            }

            _restartingView = new ASubPage(this, Device.BooleanInput[Digitals.SubPageRestarting], string.Empty, TimeSpan.Zero);
            _restartingText = new UILabel(this, Serials.RestartingText)
            {
                Text = "System Restarting"
            };

            _homeButton = new UIButton(this, Digitals.HomeButton);
            _backButton = new UIButton(this, Digitals.BackButton)
            {
                VisibleJoin = Device.BooleanInput[Digitals.BackButtonVisible]
            };
            _backButton.Show();

            _homeButton.ButtonEvent += HomeButtonOnButtonEvent;

            _textEntryView = new TextFieldEntryViewController(this);

            _actionSheets[0] = new ActionSheetDefault(this);
        }
示例#6
0
        private bool CheckIfNewVersion(Assembly appAssembly)
        {
            try
            {
                var runningVersion = appAssembly.GetName().Version;

                CloudLog.Info("Checking version of {0} to see if \"{1}\" is new", appAssembly.GetName().Name,
                              runningVersion);

                var filePath = string.Format("{0}\\{1}_version.info", AppStoragePath, appAssembly.GetName().Name);

                if (!File.Exists(filePath))
                {
                    using (var newFile = File.OpenWrite(filePath))
                    {
                        newFile.Write(runningVersion.ToString(), Encoding.UTF8);
                    }
                    CloudLog.Notice("Version file created at \"{0}\", app must be updated or new", filePath);
                    return(true);
                }

                bool appIsNewVersion;

                using (var file = new StreamReader(filePath, Encoding.UTF8))
                {
                    var contents = file.ReadToEnd().Trim();
                    var version  = new Version(contents);
                    appIsNewVersion = runningVersion.CompareTo(version) != 0;
                    if (appIsNewVersion)
                    {
                        CloudLog.Warn("APP UPDATED TO {0}", runningVersion.ToString());
                    }
                    else
                    {
                        CloudLog.Notice("App version remains as {0}", runningVersion.ToString());
                    }
                }

                if (appIsNewVersion)
                {
                    File.Delete(filePath);

                    using (var newFile = File.OpenWrite(filePath))
                    {
                        newFile.Write(runningVersion.ToString(), Encoding.UTF8);
                    }
                    CloudLog.Notice("Version file deleted and created at \"{0}\", with new version number", filePath);
                }

                return(appIsNewVersion);
            }
            catch (Exception e)
            {
                CloudLog.Error("Error checking if app is new version, returning true, {0}", e.Message);
                return(true);
            }
        }
示例#7
0
 private void StartCheckingThread()
 {
     if (_checkStatusThread != null && _checkStatusThread.ThreadState == Thread.eThreadStates.ThreadRunning)
     {
         return;
     }
     _checkWait = new CEvent();
     CloudLog.Info("{0} Starting status checking thread", GetType().Name);
     _checkStatusThread = new Thread(CheckStatusThread, null)
     {
         Name = "Sony Bravia Polling"
     };
 }
示例#8
0
        private void FusionAssetOnDeviceCommunicatingChange(IDevice device, bool communicating)
        {
            if (_programStopping)
            {
                return;
            }

            foreach (var asset in (from fusionAsset in _fusionAssets
                                   where device == fusionAsset.Value
                                   select Fusion.UserConfigurableAssetDetails[fusionAsset.Key].Asset).OfType <FusionStaticAsset>())
            {
                if (!communicating)
                {
                    CloudLog.Warn(
                        "Fusion monitoring status change for asset \"{0}\", Communicating = {1}, adding to queue and will wait 150 seconds before notifying Fusion",
                        device.Name, communicating);
                }
                else
                {
                    CloudLog.Info(
                        "Fusion monitoring status change for asset \"{0}\", Communicating = {1}, adding to queue and will wait 150 seconds before notifying Fusion",
                        device.Name, communicating);
                }

                _assetCommsStatus[asset] = new FusionAssetCommsStatus(communicating, DateTime.Now,
                                                                      GetTimeDelayForDeviceTimeout(device));

                if (!(device is IPowerDevice))
                {
                    asset.PowerOn.InputSig.BoolValue = communicating;
                }

                if (!communicating)
                {
                    SendFusionErrorMessage(FusionErrorLevel.Error, "Asset: \"{0}\" is offline", device.Name);
                }

                else
                {
                    SendFusionErrorMessage(FusionErrorLevel.Ok, "Asset: \"{0}\" is online", device.Name);
                    asset.FusionGenericAssetSerialsAsset3.StringInput[50].StringValue = device.DeviceAddressString;
                    asset.FusionGenericAssetSerialsAsset3.StringInput[51].StringValue = device.SerialNumber;
                    asset.FusionGenericAssetSerialsAsset3.StringInput[52].StringValue = device.VersionInfo;
                }
            }

            CheckFusionAssetsForOnlineStatusAndReportErrors();
        }
示例#9
0
        protected virtual void DisplayDeviceOnPowerStatusChange(IPowerDevice device, DevicePowerStatusEventArgs args)
        {
            switch (args.NewPowerStatus)
            {
            case DevicePowerStatus.PowerWarming:
            case DevicePowerStatus.PowerOn:
                if (args.PreviousPowerStatus == DevicePowerStatus.PowerWarming)
                {
                    return;
                }
                if (HoistController != null)
                {
                    CloudLog.Info("{0} power now {1}, Lowering Hoist", Name, args.NewPowerStatus);
                    HoistController.Down();
                }
                if (ScreenController != null)
                {
                    CloudLog.Info("{0} power now {1}, Lowering Screen", Name, args.NewPowerStatus);
                    ScreenController.Down();
                }
                break;

            case DevicePowerStatus.PowerOff:
                if (ScreenController != null && args.PreviousPowerStatus == DevicePowerStatus.PowerOn)
                {
                    CloudLog.Info("{0} power now {1}, Raising Screen", Name, args.NewPowerStatus);
                    ScreenController.Up();
                }
                if (HoistController != null)
                {
                    CloudLog.Info("{0} power now {1}, Raising Hoist", Name, args.NewPowerStatus);
                    HoistController.Up();
                }
                break;

            case DevicePowerStatus.PowerCooling:
                if (ScreenController != null)
                {
                    CloudLog.Info("{0} power now {1}, Raising Screen", Name, args.NewPowerStatus);
                    ScreenController.Up();
                }
                break;
            }
        }
示例#10
0
 private object ReceiveDataProcessingThread(object userSpecific)
 {
     CloudLog.Info("{0} Started", Thread.CurrentThread.Name);
     while (!_programStopping)
     {
         var count = _socket.ReceiveData();
         if (count > 0)
         {
             Debug.WriteSuccess("Visca Rx " + _socket.IPAddressLastMessageReceivedFrom,
                                Tools.GetBytesAsReadableString(_socket.IncomingDataBuffer, 0, count, false));
         }
         else if (count < 0)
         {
             CloudLog.Warn("{0} Received Data Count {1}", Thread.CurrentThread.Name, count);
         }
     }
     CloudLog.Warn("{0} Exiting", Thread.CurrentThread.Name);
     return(null);
 }
示例#11
0
        public void Start()
        {
            if (_started)
            {
                CloudLog.Warn("{0} instance on TCP port {1}, already started", GetType().Name, _socket.PortNumber);
                return;
            }

            _started = true;

            try
            {
                CloudLog.Notice("Starting {0} instance on TCP port {1}", GetType().Name, _portNumber);

                if (_socket == null || _socket.ServerSocketStatus == SocketStatus.SOCKET_STATUS_SOCKET_NOT_EXIST)
                {
                    CloudLog.Info("Created new socket for {0} on port {1}", GetType().Name, _portNumber);
                    _socket = new TCPServer(IPAddress.Any.ToString(), _portNumber, _bufferSize,
                                            EthernetAdapterType.EthernetUnknownAdapter, _numberOfConnections);
                    _socket.SocketSendOrReceiveTimeOutInMs = 60000;
                    _socket.SocketStatusChange            += SocketOnSocketStatusChange;
                    if (_waitForConnectThread == null || _waitForConnectThread.ThreadState != Thread.eThreadStates.ThreadRunning)
                    {
                        _waitForConnectThread = new Thread(ListenForConnections, null)
                        {
                            Name     = string.Format("{0} Connection Handler", GetType().Name),
                            Priority = Thread.eThreadPriority.MediumPriority
                        };
                    }
                    CloudLog.Info("{0} on port {1}\r\nStatus: {2}\r\nMax Connections: {3}", GetType().Name,
                                  _socket.PortNumber, _socket.State, _socket.MaxNumberOfClientSupported);
                }
                else
                {
                    CloudLog.Warn("TCP Server. Could not start. Current Socket Status:{0}", _socket.ServerSocketStatus);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Could not start socket");
            }
        }
示例#12
0
        protected virtual void OnRoomChange(UIController uiController, RoomBase previousRoom, RoomBase newRoom)
        {
            var handler = RoomChange;
            var args    = new UIControllerRoomChangeEventArgs(previousRoom, newRoom);

            CloudLog.Info("{0} has changed rooms from {1} to {2}", uiController,
                          previousRoom != null ? previousRoom.ToString() : "None",
                          newRoom != null ? newRoom.ToString() : "None");

            try
            {
                if (handler != null)
                {
                    handler(uiController, args);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error calling RoomChange event in {0}", GetType().Name);
            }

            if (!System.Booted)
            {
                return;
            }

            try
            {
                if (newRoom != null && newRoom.Source != null)
                {
                    UIShouldShowSource(newRoom.Source);
                }
                else
                {
                    UIShouldShowHomePage(ShowHomePageEventType.OnRoomChange);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
示例#13
0
        private void OnSourceChange(RoomBase room, SourceBase previousSource, SourceBase newSource)
        {
            var handler = SourceChange;
            var args    = new RoomSourceChangeEventArgs(previousSource, newSource);

            CloudLog.Info("{0} has changed sources from {1} to {2}", room,
                          previousSource != null ? previousSource.ToString() : "Off",
                          newSource != null ? newSource.ToString() : "Off");

            StartSourceChangeProcess(previousSource, newSource);

            try
            {
                if (handler != null)
                {
                    handler(room, args);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
示例#14
0
 private void InternalClockInitialize()
 {
     _clockInitThread = new Thread(specific =>
     {
         CloudLog.Debug("InternalClockInitialize(), Waiting for seconds to be 0", GetType().Name);
         while (DateTime.Now.Second != 0)
         {
             Thread.Sleep(50);
             CrestronEnvironment.AllowOtherAppsToRun();
         }
         CloudLog.Notice("InternalClockInitialize(), Seconds should now be zero, time is now {1}, creating CTimer to track time",
                         GetType().Name,
                         DateTime.Now.ToString("T"));
         _clockTimer = new CTimer(s => OnTimeChange(), null, 60000, 60000);
         OnTimeChange();
         CloudLog.Info("InternalClockInitialize(), OnTimeChange() will be called every time time is 0 seconds", GetType().Name);
         return(null);
     }, null, Thread.eThreadStartOptions.CreateSuspended)
     {
         Name     = "Clock Init Thread",
         Priority = Thread.eThreadPriority.HighPriority
     };
     _clockInitThread.Start();
 }
示例#15
0
        private static object ProcessUdpData(object o)
        {
            var buffer    = new byte[1000];
            var byteIndex = 0;

            while (!_programStopping)
            {
                try
                {
                    var count = _udpServer.ReceiveData();
                    for (var i = 0; i < count; i++)
                    {
                        var b = _udpServer.IncomingDataBuffer[i];
                        if (b == 13)
                        {
                            try
                            {
                                var str = Encoding.ASCII.GetString(buffer, 0, byteIndex);

                                var match = Regex.Match(str, @"UpdateServer: *([\w-.]+)");
                                if (match.Success)
                                {
                                    _serverAddress = match.Groups[1].Value;

                                    if (_checkUpdatesTimer == null)
                                    {
                                        _checkUpdatesTimer = new CTimer(specific =>
                                        {
                                            try
                                            {
                                                GetAppUpdates();
                                            }
                                            catch (Exception e)
                                            {
                                                CloudLog.Error("Could not check for updates, {0}", e.Message);
                                            }
                                        }, null, 1000,
                                                                        (long)TimeSpan.FromHours(1).TotalMilliseconds);
                                    }
                                    byteIndex = 0;
                                    continue;
                                }

                                match = Regex.Match(str, @"UpdatePush\s+Version:\s*([\d\.]+)");
                                if (match.Success)
                                {
                                    Debug.WriteWarn("Update Push!!! Version", match.Groups[1].Value);
                                    CloudLog.Notice("Software Update Push command received. Version = {0}", match.Groups[1].Value);
                                    _pushedVersion = new Version(match.Groups[1].Value);

                                    if (_pushedVersion.CompareTo(Assembly.GetExecutingAssembly().GetName().Version) == 0)
                                    {
                                        CloudLog.Notice("New version is current so will skip the push!");
                                    }
                                    else
                                    {
                                        if (_pushUpdateProcessThread != null &&
                                            _pushUpdateProcessThread.ThreadState == Thread.eThreadStates.ThreadRunning)
                                        {
                                            byteIndex = 0;
                                            continue;
                                        }
                                        Debug.WriteInfo("Update push ok to run, launching process now");
                                        CloudLog.Info("Starting software update push process", match.Groups[1].Value);
                                        _pushUpdateProcessThread = new Thread(UpdateFromPushedUpdateProcess, null);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                CloudLog.Exception(e);
                            }

                            byteIndex = 0;
                        }
                        else
                        {
                            buffer[byteIndex] = b;
                            byteIndex++;
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e is ThreadAbortException)
                    {
                        return(null);
                    }
                    CloudLog.Exception(e);
                }
            }

            return(null);
        }
示例#16
0
        private object ReceiveBufferProcess(object obj)
        {
            var bytes      = new Byte[1000];
            var byteIndex  = 0;
            var dataLength = 0;

            CloudLog.Info("Started {0}", Thread.CurrentThread.Name);

            while (true)
            {
                try
                {
                    var b = _rxQueue.Dequeue();

                    if (_programStopping)
                    {
                        return(null);
                    }

                    if (b == 0xAA)
                    {
                        byteIndex  = 0;
                        dataLength = 0;
                    }
                    else
                    {
                        byteIndex++;
                    }

                    bytes[byteIndex] = b;
                    if (byteIndex == 3)
                    {
                        dataLength = bytes[byteIndex];
                    }

                    if (byteIndex == (dataLength + 4))
                    {
                        int chk = bytes[byteIndex];

                        var test = 0;
                        for (var i = 1; i < byteIndex; i++)
                        {
                            test = test + bytes[i];
                        }

                        if (chk == (byte)test)
                        {
                            var copiedBytes = new byte[byteIndex];
                            Array.Copy(bytes, copiedBytes, byteIndex);
                            if (ReceivedPacket != null)
                            {
                                ReceivedPacket(this, copiedBytes);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
#if DEBUG
                        CrestronConsole.Print("Error in Samsung Rx: {0}",
                                              Tools.GetBytesAsReadableString(bytes, 0, byteIndex, false));
#endif
                        CloudLog.Error("Error in {0} TX Thread", GetType().Name);
                    }
                }

                CrestronEnvironment.AllowOtherAppsToRun();
            }
        }
示例#17
0
        private object SshCommsProcess(object userSpecific)
        {
            var errorOnConnect = false;

            try
            {
                Thread.Sleep(1000);

                CloudLog.Info("{0} attempting connection to {1}", GetType().Name, _address);

                var firstFail = false;

                while (!_client.IsConnected && _reconnect)
                {
                    try
                    {
                        ConnectionStatus = SshClientStatus.AttemptingConnection;
                        _client.Connect();
                    }
                    catch
                    {
                        ConnectionStatus = SshClientStatus.Disconnected;
                        if (!firstFail)
                        {
                            CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected",
                                          GetType().Name, _address);
                            firstFail = true;
                        }

                        if (_threadWait.WaitOne(30000))
                        {
                            CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                            _reconnect = false;
                            break;
                        }
                    }
                }

                if (!_client.IsConnected && !_reconnect)
                {
                    _client.Dispose();
                    _client          = null;
                    ConnectionStatus = SshClientStatus.Disconnected;
                    return(null);
                }

                CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address);

                _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, 100000);

                //_shell.DataReceived += (sender, args) => _threadWait.Set();

                var data = string.Empty;

                try
                {
                    while (_programRunning && _client.IsConnected)
                    {
                        while (_shell.CanRead && _shell.DataAvailable)
                        {
                            var bytes  = new byte[100000];
                            var length = _shell.Read(bytes, 0, bytes.Length);
#if DEBUG
                            _stopWatch.Start();
                            Debug.WriteSuccess("Codec rx {0} bytes", length);
#endif
                            var incoming = Encoding.ASCII.GetString(bytes, 0, length);

                            if (!_loggedIn && incoming.Contains("Failed to connect to system software"))
                            {
                                CloudLog.Error("Error received from codec at \"{0}\" on connect:\r\n{1}",
                                               _address, incoming);
                                errorOnConnect = true;
                                break;
                            }
#if DEBUG
                            Debug.WriteNormal(Debug.AnsiBlue + incoming + Debug.AnsiReset);
#endif
                            data = data + incoming;

                            if (!_loggedIn)
                            {
                                foreach (var line in Regex.Split(data, "\r\n|\r|\n"))
                                {
                                    if (line == "*r Login successful")
                                    {
                                        _loggedIn = true;
                                        try
                                        {
                                            Debug.WriteSuccess("Connected!", "{0} logged into {1}", GetType().Name,
                                                               _address);
                                            CloudLog.Info("{0} logged into {1}", GetType().Name, _address);

                                            _sendQueue.Enqueue(@"echo off");

                                            var adapterType = _client.EthernetAdapter;
                                            var adapterId   =
                                                CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(adapterType);
                                            var currentIp = CrestronEthernetHelper.GetEthernetParameter(
                                                CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                                                adapterId);
                                            var assembly     = Assembly.GetExecutingAssembly().GetName();
                                            var softwareInfo = assembly.Name + " " + assembly.Version;
                                            var model        = InitialParametersClass.ControllerPromptName;
                                            _sendQueue.Enqueue(string.Format(
                                                                   "xCommand Peripherals Connect ID: {0} Name: \"Crestron Control System\" HardwareInfo: \"{1}\" NetworkAddress: \"{2}\" SoftwareInfo: \"{3}\" Type: ControlSystem",
                                                                   _heartbeatId, string.Format("Crestron {0}", model), currentIp,
                                                                   softwareInfo));

                                            _sendQueue.Enqueue(@"xFeedback register /Configuration");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/SystemUnit");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Diagnostics");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Audio");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Standby");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Video");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Cameras");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Call");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Conference");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/UserInterface");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Bookings");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/OutgoingCallIndication");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/IncomingCallIndication");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallSuccessful");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallDisconnect");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/Bookings");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallHistory");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Extensions");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Presentation/ExternalSource");

                                            _sendQueue.Enqueue(@"xStatus");

                                            _heartBeatTimer =
                                                new CTimer(
                                                    specific =>
                                                    _sendQueue.Enqueue(
                                                        string.Format("xCommand Peripherals HeartBeat ID: {0}",
                                                                      _heartbeatId)),
                                                    null, 60000, 60000);

                                            ConnectionStatus = SshClientStatus.Connected;
                                        }
                                        catch (Exception e)
                                        {
                                            CloudLog.Exception(e);
                                        }
                                    }
                                }

                                data = string.Empty;
                            }
                            else if (data.Contains("** end"))
                            {
                                var chunks = Regex.Matches(data, @"(\*(\w) [\S\s]*?)(?=\*\* end)");

                                data = string.Empty;

                                if (chunks.Count > 0)
                                {
                                    foreach (Match chunk in chunks)
                                    {
                                        var type = ReceivedDataType.Status;

                                        switch (chunk.Groups[2].Value)
                                        {
                                        case "e":
                                            type = ReceivedDataType.Event;
                                            break;

                                        case "r":
                                            type = ReceivedDataType.Response;
                                            break;

                                        case "c":
                                            type = ReceivedDataType.Configuration;
                                            break;
                                        }
                                        OnReceivedData(this, type, chunk.Groups[1].Value);
                                    }
                                }
                            }
#if DEBUG
                            else
                            {
                                Debug.WriteWarn("Waiting for more data...");
                            }

                            _stopWatch.Stop();
                            Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds);
                            _stopWatch.Reset();
#endif
                            CrestronEnvironment.AllowOtherAppsToRun();
                        }

                        if (errorOnConnect)
                        {
                            try
                            {
                                _client.Disconnect();
                            }
                            catch (Exception e)
                            {
                                CloudLog.Warn("Error closing connection to codec after error, {0}", e.Message);
                            }

                            break;
                        }

                        if (!_programRunning || !_client.IsConnected)
                        {
                            break;
                        }

                        while (_shell.CanWrite && !_sendQueue.IsEmpty)
                        {
                            var s = _sendQueue.Dequeue();
#if DEBUG
                            Debug.WriteWarn("Codec Tx", s);
#endif
                            _shell.WriteLine(s);
                        }
                    }

                    CloudLog.Debug("{0} left while(connected) loop", Thread.CurrentThread.Name);
                }
                catch (ObjectDisposedException e)
                {
                    CloudLog.Warn("{0} ObjectDisposedException, {1}, {2}", GetType().Name,
                                  string.IsNullOrEmpty(e.ObjectName) ? "unknown" : e.ObjectName, e.Message);
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error handling comms process");
                }

                _loggedIn = false;

                try
                {
                    if (_heartBeatTimer != null && !_heartBeatTimer.Disposed)
                    {
                        _heartBeatTimer.Stop();
                        _heartBeatTimer.Dispose();
                    }

                    if (_client != null)
                    {
                        CloudLog.Info("Disposing {0}", _client.ToString());
                        _client.Dispose();
                        _client = null;
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error trying to dispose items in leaving thread");
                }

                CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name);
            }

            ConnectionStatus = SshClientStatus.Disconnected;

            if (errorOnConnect)
            {
                CloudLog.Warn("Error message while connecting to {0}, Disconnected and will retry in 60 seconds", _address);

                if (_threadWait.WaitOne(60000))
                {
                    CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                    _reconnect = false;
                }
            }

            if (!_reconnect)
            {
                CloudLog.Notice("Leaving connect thread for codec at {0}", _address);
                return(null);
            }

            CloudLog.Notice("Waiting for 10 seconds before reconnect attempt to {0}", _address);
            if (_threadWait.WaitOne(10000))
            {
                CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                _reconnect = false;
                return(null);
            }

            CloudLog.Notice("Attempting reconnect to codec at {0}", _address);
            ConnectionStatus = SshClientStatus.AttemptingConnection;

            Connect();

            return(null);
        }
示例#18
0
        public override void TestScriptProcess(IDictionary <string, string> args)
        {
            _testScriptShouldRun = true;
            var count    = 0;
            var maxCount = 0;

            CloudLog.Notice("Test scripting process begin. Testing starts in 5 seconds");

            if (args.ContainsKey("count"))
            {
                try
                {
                    maxCount = int.Parse(args["count"]);
                }
                catch
                {
                    CloudLog.Warn("Test Script argument error, count is not a number. Script will run until cancelled!");
                }
            }

            Thread.Sleep(5000);

            var room        = Rooms.First();
            var sources     = room.Sources.ToArray();
            var sourceCount = sources.Length;
            var random      = new Random();

            while (_testScriptShouldRun)
            {
                count++;
                CloudLog.Info("Test Script Loop {0}", count);

                while (true)
                {
                    var randomSourceIndex = random.Next(0, sourceCount);

                    SourceBase source = null;

                    if (randomSourceIndex == 0 && room.Source == null)
                    {
                        continue;
                    }

                    if (randomSourceIndex > 0)
                    {
                        source = sources[randomSourceIndex - 1];
                        if (source == room.Source)
                        {
                            continue;
                        }
                    }

                    CloudLog.Info("Selecting random source: {0}", source != null ? source.ToString() : "None");

                    try
                    {
                        room.Source = source;
                    }
                    catch (Exception e)
                    {
                        CloudLog.Error("Error setting source in TestScriptProcess(), {0}", e.Message);
                    }

                    break;
                }

                CloudLog.Debug("Selected source {0}, waiting for 10 seconds",
                               room.Source != null ? room.Source.ToString() : "None");

                Thread.Sleep(10000);

                if (room.Source != null && room.Source.Device is CiscoTelePresenceCodec)
                {
                    var codec = room.Source.Device as CiscoTelePresenceCodec;

                    if (args.ContainsKey("dial") && args["dial"].Length > 0)
                    {
                        CloudLog.Debug("Source is Codec source, will attempt call to \"{0}\"", args["dial"]);

                        try
                        {
                            codec.Calls.DialNumber(args["number"],
                                                   (code, description, id) =>
                                                   CloudLog.Debug("Dial result: {0} {1}, call id: {2}", code, description, id));
                        }
                        catch (Exception e)
                        {
                            CloudLog.Error("Could not dial call, {0}", e.Message);
                        }

                        CloudLog.Debug("Will wait for 60 seconds");

                        Thread.Sleep(60000);

                        CloudLog.Debug("Ending all calls");

                        codec.Calls.DisconnectAll();

                        Thread.Sleep(5000);
                    }
                }
                else
                {
                    Thread.Sleep(20000);
                }

                if (count != maxCount)
                {
                    continue;
                }
                CloudLog.Notice("Test scripting count reached. Exiting loop.");
                return;
            }
        }
示例#19
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);
        }
示例#20
0
        internal bool StartSession()
        {
            CodecRequest  request;
            CodecResponse response;

            CloudLog.Info("Cisco Codec StartSession() called");

            if (!string.IsNullOrEmpty(_sessionId))
            {
                try
                {
                    CloudLog.Debug("Codec has session ID already... attempting to close it");

                    request = new CodecRequest(_address, "/xmlapi/session/end", _sessionId)
                    {
                        RequestType = RequestType.Post
                    };
                    response = Dispatch(request);
#if DEBUG
                    Debug.WriteInfo("Received headers for session end:\r\n" + response.Header);
#endif
                    CloudLog.Debug("Session close request result: {0}", response.Code);
                }
                catch (Exception e)
                {
                    Debug.WriteError("Error trying to close session on codec",
                                     "Session ID to close: {0}, Error: {1}\r\nStackTrace: {2}", _sessionId, e.Message, e.StackTrace);
                    CloudLog.Error("Error trying to close the codec session, {0}", e.Message);
                }
            }
            try
            {
                request = new CodecRequest(_address, "/xmlapi/session/begin", _username, _password)
                {
                    RequestType = RequestType.Post
                };

                response = Dispatch(request);
#if DEBUG
                Debug.WriteInfo("Received headers for session begin:\r\n" + response.Header);
#endif
                if (response.Code == 401)
                {
                    CloudLog.Error("Error logging into Cisco Codec at \"{0}\" 401 - Unauthorized", _address);
                    return(false);
                }

                if (response.Code == 204)
                {
                    if (!response.Header.ContainsHeaderValue("Set-Cookie"))
                    {
                        CloudLog.Error("Received 204 for Session ID but response headers contained no Cookie");
                        return(false);
                    }
                    Debug.WriteSuccess("Codec Set-Cookie received", response.Header["Set-Cookie"]);
                    CloudLog.Notice("Codec Set-Cookie received\r\n{0}", response.Header["Set-Cookie"]);
                    var match = Regex.Match(response.Header["Set-Cookie"].Value, @"(.*?)=(.*?);");
                    if (match.Groups[1].Value != "SecureSessionId")
                    {
                        CloudLog.Error("Received 204 for Session ID but response headers contained no SessionId");
                        return(false);
                    }
                    _sessionId = match.Groups[2].Value;

                    CloudLog.Info("Codec received new Session Id OK");
                    return(true);
                }
            }
            catch (Exception e)
            {
                CloudLog.Error("Error trying to get a session ID from Cisco Codec, {0}", e.Message);
                return(false);
            }
            return(false);
        }
示例#21
0
        public static object UpdateFromPushedUpdateProcess(object o)
        {
            var random       = new Random();
            var attemptCount = 0;

            if (_status == UpdateStatus.Failed)
            {
                CloudLog.Notice("Previous update had failed, clearing status!");
                _status = UpdateStatus.NotRunning;
                Thread.Sleep(1000);
            }

            while (_status == UpdateStatus.NotRunning && !_programStopping)
            {
                try
                {
                    attemptCount++;

                    if (attemptCount == 1)
                    {
                        var ms = random.Next((int)TimeSpan.FromSeconds(30).TotalMilliseconds,
                                             (int)TimeSpan.FromMinutes(20).TotalMilliseconds);

                        Debug.WriteSuccess("Update push process running", "waiing for {0}",
                                           TimeSpan.FromMilliseconds(ms).ToString());

                        CrestronEnvironment.AllowOtherAppsToRun();
                        Thread.Sleep(ms);
                    }
                    else
                    {
                        Thread.Sleep(60000);
                    }

                    if (attemptCount > 5)
                    {
                        CloudLog.Error("Software update push failed after 5 attempts. Exiting process");
                        _status = UpdateStatus.Failed;
                        return(null);
                    }

                    if (_status != UpdateStatus.NotRunning)
                    {
                        return(null);
                    }

                    Debug.WriteInfo("Getting current list of updates...");

                    try
                    {
                        GetAppUpdates();
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e);
                        _httpClient.Dispose();
                        _httpClient = new HttpClient();
                    }

                    var info = _updates.FirstOrDefault(f => new Version(f.Version).CompareTo(_pushedVersion) == 0);

                    if (info != null)
                    {
                        Debug.WriteInfo("Found update available at URL", info.Url);
                        CloudLog.Info("Software update push can be downloaded from: {0}", info.Url);
                        var downloadResult = Download(info.Url);
                        if (downloadResult == 0)
                        {
                            try
                            {
                                OnUpdateShouldLoad();
                            }
                            catch (Exception e)
                            {
                                CloudLog.Exception(e);
                                continue;
                            }
                            return(null);
                        }

                        _status = UpdateStatus.NotRunning;

                        CloudLog.Warn("Attempt {0} to download update failed, Error {1}", attemptCount, downloadResult);
                        continue;
                    }

                    CloudLog.Error("Pushed update failed, could not find an update matching version {0}", _pushedVersion);
                    _status = UpdateStatus.Failed;
                    return(null);
                }
                catch (Exception e)
                {
                    if (attemptCount <= 5)
                    {
                        continue;
                    }
                    CloudLog.Error("Pushed update failed to get version {0}, {1}", _pushedVersion, e.Message);
                    _status = UpdateStatus.Failed;
                    return(null);
                }
            }

            return(null);
        }