Esempio n. 1
0
        /// <summary>
        /// Make sure that overriding classes call this!
        /// Registers the Crestron device, connects up to the base events, starts communication monitor
        /// </summary>
        public override bool CustomActivate()
        {
            Debug.Console(0, this, "Activating");
            if (!PreventRegistration)
            {
                //Debug.Console(1, this, "  Does not require registration. Skipping");

                var response = Hardware.RegisterWithLogging(Key);
                if (response != eDeviceRegistrationUnRegistrationResponse.Success)
                {
                    //Debug.Console(0, this, "ERROR: Cannot register Crestron device: {0}", response);
                    return(false);
                }

                IsRegistered.FireUpdate();
            }

            foreach (var f in Feedbacks)
            {
                f.FireUpdate();
            }

            Hardware.OnlineStatusChange += new OnlineStatusChangeEventHandler(Hardware_OnlineStatusChange);
            CommunicationMonitor.Start();

            return(true);
        }
Esempio n. 2
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public override bool CustomActivate()
 {
     Communication.Connect();
     CommunicationMonitor.StatusChange += (o, a) => { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); };
     CommunicationMonitor.Start();
     return(true);
 }
Esempio n. 3
0
        /// <summary>
        /// Registers the Crestron device, connects up to the base events, starts communication monitor
        /// </summary>
        public override bool CustomActivate()
        {
            Debug.Console(0, this, "Activating");
            if (!base.CustomActivate())
            {
                return(false);
            }

            var response = _display.RegisterWithLogging(Key);

            if (response != eDeviceRegistrationUnRegistrationResponse.Success)
            {
                Debug.Console(0, this, "ERROR: Cannot register Crestron device: {0}", response);
                return(false);
            }

            // TODO: implement IsRegestered feedback
            //IsRegistered.FireUpdate();

            foreach (var f in Feedbacks)
            {
                f.FireUpdate();
            }

            _display.BaseEvent          += displayEvent;
            _display.OnlineStatusChange += onlineStatusChange;
            CommunicationMonitor.Start();

            return(true);
        }
Esempio n. 4
0
        public void CommunicationMonitor_HearthBeat()
        {
            var testDp               = new TestDp(DatabaseStorage.CreateEmpty());
            var messageProvider      = new DefaultMessageProvider(new MessageSenderManager());
            var missingEntityHandler = new MissingEntityHandler();
            var messagingOptions     = Options.Create(new MessagingOptions()
            {
                CommunicationMonitorRunningPeriodInSeconds = 1
            });
            var securitySystem = new SecuritySystem(testDp, messageProvider, missingEntityHandler,
                                                    new SecurityConfiguration(), messagingOptions.Value);
            var dataHandler           = new DataHandler(testDp, messagingOptions);
            var communicationMonitor  = new CommunicationMonitor(dataHandler, messagingOptions);
            var activityHistory       = new SecurityActivityHistoryController();
            var securityActivityQueue = new SecurityActivityQueue(securitySystem, communicationMonitor, dataHandler, activityHistory);

            // ACTION
            var communicationMonitorAcc = new ObjectAccessor(communicationMonitor);

            communicationMonitorAcc.Invoke("Timer_Elapsed");

            // ASSERT
            Assert.IsTrue(testDp.IsCleanupSecurityActivitiesCalled);
            Assert.IsTrue(testDp.IsGetLastSecurityActivityIdCalled);
        }
Esempio n. 5
0
        /// <summary>
        /// Initiates the subscription process to the DSP
        /// </summary>
        void SubscribeToAttributes()
        {
            SendLine("cgd 1");

            SendLine("cgc 1");

            foreach (KeyValuePair <string, QscDspLevelControl> level in LevelControlPoints)
            {
                level.Value.Subscribe();
            }

            foreach (var dialer in Dialers)
            {
                dialer.Value.Subscribe();
            }

            if (CommunicationMonitor != null)
            {
                CommunicationMonitor.Start();
                //CommunicationMonitor = null;
            }
            else
            {
            }
            //CommunicationMonitor.Message = "cgp 1\x0D\x0A";
            CommunicationMonitor.StatusChange += (o, a) => { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); };
            //CommunicationMonitor.Start();
            if (!CommandQueueInProgress)
            {
                SendNextQueuedCommand();
            }

            // ResetSubscriptionTimer();
        }
        /// <summary>
        /// This disconnects events and unregisters the base hardware device.
        /// </summary>
        /// <returns></returns>
        public override bool Deactivate()
        {
            CommunicationMonitor.Stop();
            Hardware.OnlineStatusChange -= Hardware_OnlineStatusChange;

            return(Hardware.UnRegister() == eDeviceRegistrationUnRegistrationResponse.Success);
        }
Esempio n. 7
0
        public override bool CustomActivate()
        {
            Communication.Connect();
            CommunicationMonitor.StatusChange += (o, a) => { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); };
            CommunicationMonitor.Start();

            CrestronConsole.AddNewConsoleCommand(SendLine, "send" + Key, "", ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(s => Communication.Connect(), "con" + Key, "", ConsoleAccessLevelEnum.AccessOperator);
            return(true);
        }
Esempio n. 8
0
        /// <summary>
        /// This will run during the Activation phase
        /// </summary>
        /// <returns></returns>
        public override bool CustomActivate()
        {
            Communication.Connect();

            CommunicationMonitor.StatusChange += (o, a) => { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); };
            CommunicationMonitor.Start();

            // Call the base method in case any steps need to happen there
            return(base.CustomActivate());
        }
Esempio n. 9
0
 /// <summary>
 /// Stops the security subsystem.
 /// </summary>
 public static void Shutdown()
 {
     if (_killed)
     {
         return;
     }
     _killed = true;
     _messageProvider.ShutDown();
     _messageProvider.MessageReceived -= MessageProvider_MessageReceived;
     CommunicationMonitor.Shutdown();
     SecurityActivityQueue.Shutdown();
 }
Esempio n. 10
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override bool CustomActivate()
        {
            Communication.Connect();

            var socket = Communication as ISocketStatus;

            if (socket != null)
            {
                socket.ConnectionChange += new EventHandler <GenericSocketStatusChageEventArgs>(socket_ConnectionChange);
            }

            CommunicationMonitor.StatusChange += (o, a) => { Debug.Console(2, this, "Communication monitor state: {0}", CommunicationMonitor.Status); };
            CommunicationMonitor.Start();

            StatusGet();

            return(true);
        }
Esempio n. 11
0
        /// <summary>
        /// This disconnects events and unregisters the base hardware device.
        /// </summary>
        public override bool Deactivate()
        {
            if (!base.Deactivate())
            {
                return(false);
            }

            CommunicationMonitor.Stop();

            CommunicationMonitor.Stop();
            _display.OnlineStatusChange -= onlineStatusChange;
            _display.BaseEvent          -= displayEvent;

            var success = _display.UnRegister() == eDeviceRegistrationUnRegistrationResponse.Success;

            // TODO: implement IsRegistered feedback
            //IsRegistered.FireUpdate();

            return(success);
        }
Esempio n. 12
0
        /// <summary>
        /// Starts the security subsystem using the passed configuration.
        /// Call this method only once in your application's startup sequence.
        /// The method prepares and memorizes the main components for
        /// creating SecurityContext instances in a fastest possible way.
        /// The main components are global objects:
        /// ISecurityDataProvider instance, IMessageProvider instance and SecurityCache instance.
        /// </summary>
        protected static void StartTheSystem(SecurityConfiguration configuration)
        {
            _generalContext = null;

            // The messageprovider provider must receive ongoing activities at this time.
            StartedAt = DateTime.UtcNow;

            int lastActivityIdFromDb;
            var uncompleted = DataHandler.LoadCompletionState(configuration.SecurityDataProvider, out lastActivityIdFromDb);

            _messageProvider = configuration.MessageProvider;
            _messageProvider.MessageReceived += MessageProvider_MessageReceived;

            Configuration.Identities.SystemUserId    = configuration.SystemUserId ?? -1;
            Configuration.Identities.VisitorUserId   = configuration.VisitorUserId ?? 6;
            Configuration.Identities.EveryoneGroupId = configuration.EveryoneGroupId ?? 8;
            Configuration.Identities.OwnerGroupId    = configuration.OwnerGroupId ?? 9;

            Configuration.Messaging.CommunicationMonitorRunningPeriodInSeconds = configuration.CommunicationMonitorRunningPeriodInSeconds ?? 30;
            Configuration.Messaging.SecuritActivityLifetimeInMinutes           = configuration.SecuritActivityLifetimeInMinutes ?? 42;
            Configuration.Messaging.SecuritActivityTimeoutInSeconds            = configuration.SecuritActivityTimeoutInSeconds ?? 120;

            _securityDataProviderPrototype = configuration.SecurityDataProvider;
            PermissionTypeBase.InferForcedRelations();

            using (var op = SnTrace.Security.StartOperation("Security initial loading."))
            {
                _cacheHolder  = SecurityCache.Initialize(configuration.SecurityDataProvider);
                op.Successful = true;
            }

            CommunicationMonitor.Initialize();

            _generalContext = new SecurityContext(SystemUser);
            SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb);

            _killed = false;
        }
Esempio n. 13
0
        public void Start()
        {
            GeneralSecurityContext = null;

            // The message provider must receive ongoing activities at this time.
            StartedAt = DateTime.UtcNow;

            var uncompleted = DataHandler.LoadCompletionState(out var lastActivityIdFromDb);

            PermissionTypeBase.InferForcedRelations();

            using (var op = SnTrace.Security.StartOperation("Security initial loading."))
            {
                var cache = new SecurityCache(DataHandler);
                cache.Initialize();
                Cache         = cache;
                op.Successful = true;
            }

            EntityManager             = new SecurityEntityManager(Cache, DataHandler, MissingEntityHandler);
            Cache.EntityManager       = EntityManager; // Property injection
            DataHandler.EntityManager = EntityManager; // Property injection

            PermissionQuery        = new PermissionQuery(EntityManager, Cache);
            CommunicationMonitor   = new CommunicationMonitor(DataHandler, Options.Create(MessagingOptions));
            GeneralSecurityContext = new SecurityContext(SystemUser, this);

            SecurityActivityQueue = new SecurityActivityQueue(this, CommunicationMonitor, DataHandler, ActivityHistory);
            SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb);
            ActivityHistory.SecurityActivityQueue = SecurityActivityQueue; // Property injection

            MessageProvider.MessageReceived += MessageProvider_MessageReceived;
            MessageProvider.Initialize();
            MessageProvider.Start(StartedAt);

            _killed = false;
        }
Esempio n. 14
0
        private void Port_LineReceived(object dev, GenericCommMethodReceiveTextArgs args)
        {
            if (Debug.Level == 2)
            {
                Debug.Console(2, this, "RX: '{0}'",
                              ShowHexResponse ? ComTextHelper.GetEscapedText(args.Text) : args.Text);
            }

            //Debug.Console(1, this, "RX: '{0}'", args.Text);

            try
            {
                DeviceRx = args.Text;

                CommandPassthruFeedback.FireUpdate();

                if (args.Text.IndexOf("Welcome to the Tesira Text Protocol Server...", StringComparison.Ordinal) > -1)
                {
                    // Indicates a new TTP session
                    // moved to CustomActivate() method
                    CommunicationMonitor.Start();
                    CrestronInvoke.BeginInvoke((o) => HandleAttributeSubscriptions());
                }
                else if (args.Text.IndexOf("! ", StringComparison.Ordinal) > -1)
                {
                    // response is from a subscribed attribute

                    //(if(args.Text

                    const string pattern = "! [\\\"](.*?[^\\\\])[\\\"] (.*)";

                    var match = Regex.Match(args.Text, pattern);

                    if (!match.Success)
                    {
                        return;
                    }

                    var customName = match.Groups[1].Value;
                    var value      = match.Groups[2].Value;

                    AdvanceQueue(args.Text);

                    foreach (var controlPoint in Faders.Where(controlPoint => customName == controlPoint.Value.LevelCustomName || customName == controlPoint.Value.MuteCustomName))
                    {
                        controlPoint.Value.ParseSubscriptionMessage(customName, value);
                        return;
                    }
                    foreach (var controlPoint in Dialers.Where(controlPoint => customName == controlPoint.Value.AutoAnswerCustomName || customName == controlPoint.Value.ControlStatusCustomName || customName == controlPoint.Value.DialerCustomName))
                    {
                        controlPoint.Value.ParseSubscriptionMessage(customName, value);
                        return;
                    }
                    foreach (var controlPoint in States.Where(controlPoint => customName == controlPoint.Value.StateCustomName))
                    {
                        controlPoint.Value.ParseSubscriptionMessage(customName, value);
                        return;
                    }

                    foreach (var controlPoint in Switchers.Where(controlPoint => customName == controlPoint.Value.SelectorCustomName))
                    {
                        controlPoint.Value.ParseSubscriptionMessage(customName, value);
                        return;
                    }

                    foreach (var controlPoint in Meters.Where(controlPoint => customName == controlPoint.Value.MeterCustomName))
                    {
                        controlPoint.Value.ParseSubscriptionMessage(customName, value);
                        return;
                    }

                    // same for dialers
                    // same for switchers
                }
                else if (args.Text.IndexOf("+OK", StringComparison.Ordinal) > -1)
                {
                    if (args.Text == "+OK")       // Check for a simple "+OK" only 'ack' repsonse or a list response and ignore
                    {
                        return;
                    }
                    // response is not from a subscribed attribute.  From a get/set/toggle/increment/decrement command
                    //string pattern = "(?<=\" )(.*?)(?=\\+)";
                    //string data = Regex.Replace(args.Text, pattern, "");

                    AdvanceQueue(args.Text);
                }
                else if (args.Text.IndexOf("-ERR", StringComparison.Ordinal) > -1)
                {
                    // Error response
                    Debug.Console(2, this, "Error From DSP: '{0}'", args.Text);
                    switch (args.Text)
                    {
                    case "-ERR ALREADY_SUBSCRIBED":
                    {
                        WatchDogSniffer = false;
                        AdvanceQueue(args.Text);
                        break;
                    }


                    default:
                    {
                        WatchDogSniffer = false;

                        AdvanceQueue(args.Text);
                        break;
                    }
                    }
                }
            }
            catch (Exception e)
            {
                if (Debug.Level == 2)
                {
                    Debug.Console(2, this, "Error parsing response: '{0}'\n{1}", args.Text, e);
                }
            }
        }
Esempio n. 15
0
        public void EF_LoadActivities_SmartGapResolution()
        {
            int             lastActivityIdFromDb;
            CompletionState uncompleted;

            var sb = new StringBuilder();

            context = Start();
            CommunicationMonitor.Stop();
            var sctx         = context.Security;
            var user1Id      = TestUser.User1.Id;
            var rootEntityId = Id("E01");

            // create some activities with gap
            sctx.CreateSecurityEntity(rootEntityId, default(int), user1Id);
            for (int entityId = rootEntityId + 1; entityId < rootEntityId + 11; entityId++)
            {
                sctx.CreateSecurityEntity(entityId, rootEntityId, user1Id);
                Db().ExecuteTestScript(@"
                    -- 2 gap
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('asdf1', GETDATE(),'Wait')
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('qwer1', GETDATE(),'Wait')
                    DELETE EFMessages WHERE Id in (select top 2 Id from [EFMessages] order by Id desc)");
            }

            // these are be unprocessed
            Db().ExecuteTestScript("UPDATE EFMessages set ExecutionState = 'Wait', LockedBy = null, LockedAt = null");

            sb.Clear();
            uncompleted = DataHandler.LoadCompletionState(SecurityContext.General.DataProvider, out lastActivityIdFromDb);
            SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb);

            var cs1 = SecurityActivityQueue.GetCurrentCompletionState();

            // expectation: there is no any gap.
            Assert.AreEqual(0, cs1.Gaps.Length);

            // create a gap
            Db().ExecuteTestScript(@"
                    -- 2 gap
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('asdf1', GETDATE(),'Wait')
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('qwer1', GETDATE(),'Wait')
                    DELETE EFMessages WHERE Id in (select top 2 Id from [EFMessages] order by Id desc)
                    -- copy last
                    INSERT INTO EFMessages([SavedBy],[SavedAt],[ExecutionState],[LockedBy],[LockedAt],[Body])
                         SELECT TOP 1 [SavedBy],GETDATE(),[ExecutionState],[LockedBy],[LockedAt],[Body] FROM EFMessages ORDER BY Id DESC
                    -- 2 gap
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('asdf2', GETDATE(),'Wait')
                    INSERT INTO EFMessages ([SavedBy], [SavedAt], [ExecutionState]) VALUES ('qwer2', GETDATE(),'Wait')
                    DELETE EFMessages WHERE Id in (select top 2 Id from [EFMessages] order by Id desc)");

            // last activity
            sctx.CreateSecurityEntity(101, rootEntityId, user1Id);

            var cs2 = SecurityActivityQueue.GetCurrentCompletionState();

            Assert.AreEqual(4, cs2.Gaps.Length);
            Assert.AreEqual(cs1.LastActivityId + 6, cs2.LastActivityId);

            SecurityActivityQueue.HealthCheck();

            var cs3 = SecurityActivityQueue.GetCurrentCompletionState();

            Assert.AreEqual(0, cs3.Gaps.Length);
            Assert.AreEqual(cs2.LastActivityId, cs3.LastActivityId);

            CommunicationMonitor.Start();
        }