Ejemplo n.º 1
0
 public DelayedAction(TimeSpan delay, Action action, ITimerService timerService)
 {
     _timerService       = timerService ?? throw new ArgumentNullException(nameof(timerService));
     _action             = action ?? throw new ArgumentNullException(nameof(action));
     _delay              = delay;
     _timerService.Tick += CheckForTimeout;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Starts a timer with the specified <paramref name="interval"/>. The specified <paramref name="method"/> will be invoked on the specified <paramref name="target"/> each timer tick.
        /// </summary>
        /// <param name="timerService">The timer service.</param>
        /// <param name="target">The target on which to tick.</param>
        /// <param name="method">The method to invoke each timer tick.</param>
        /// <param name="interval">The interval at which to tick.</param>
        /// <returns>A reference to the started timer.</returns>
        public static TimerReference Start(this ITimerService timerService, object target, MethodInfo method, TimeSpan interval)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (!TimerSystem.IsValidInterval(interval))
            {
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "The interval should be a nonzero positive value.");
            }

            if (!method.DeclaringType.IsInstanceOfType(target))
            {
                throw new ArgumentException("The specified method is not a member of the specified target", nameof(method));
            }

            var parameterInfos = method.GetParameters()
                                 .Select(info => new MethodParameterSource(info)
            {
                IsService = true
            })
                                 .ToArray();

            var compiled = MethodInvokerFactory.Compile(method, parameterInfos);

            return(timerService.Start(serviceProvider => compiled(target, null, serviceProvider, null), interval));
        }
Ejemplo n.º 3
0
 public DivChampPhaseService(ITimerService timerService,
                             IRepository repository)
 {
     _timerService = timerService;
     _repository   = repository;
     _season       = _repository.Get(new CurrentSeasonWithStandingsTeams());
 }
Ejemplo n.º 4
0
        public ShellPageViewModel(
            IUserSettings userSettings,
            ITimerService timer,
            ITelemetry telemetry,
            ISystemInfoProvider systemInfoProvider)
        {
            Guard.IsNotNull(userSettings, nameof(userSettings));
            Guard.IsNotNull(timer, nameof(timer));
            Guard.IsNotNull(telemetry, nameof(telemetry));

            _userSettings = userSettings;
            _ratingTimer  = timer;
            _telemetry    = telemetry;

            _userSettings.SettingSet += OnSettingSet;

            var lastDismissDateTime = _userSettings.GetAndDeserialize <DateTime>(UserSettingsConstants.RatingDismissed);

            if (!systemInfoProvider.IsFirstRun() &&
                !systemInfoProvider.IsTenFoot() &&
                !_userSettings.Get <bool>(UserSettingsConstants.HasRated) &&
                lastDismissDateTime.AddDays(7) <= DateTime.UtcNow)
            {
                _ratingTimer.Interval         = 1800000; // 30 minutes
                _ratingTimer.IntervalElapsed += OnIntervalLapsed;
                _ratingTimer.Start();
            }
        }
Ejemplo n.º 5
0
        public CatLitterBoxTwitterSender(ITimerService timerService, ITwitterClientService twitterClientService, ILogService logService)
        {
            if (timerService == null)
            {
                throw new ArgumentNullException(nameof(timerService));
            }
            if (twitterClientService == null)
            {
                throw new ArgumentNullException(nameof(twitterClientService));
            }
            if (logService == null)
            {
                throw new ArgumentNullException(nameof(logService));
            }

            _twitterClientService = twitterClientService;

            _log = logService.CreatePublisher(nameof(logService));

            _timeout          = new Timeout(timerService);
            _timeout.Elapsed += (s, e) =>
            {
                _timeInLitterBox.Stop();
                Task.Run(() => Tweet(_timeInLitterBox.Elapsed));
            };

            _timeout.Start(TimeSpan.FromSeconds(30));
        }
Ejemplo n.º 6
0
 public TimeManager(IMessagePublisher messagePublisher, ITimerService rtservice)
 {
     _cancellationTokenSource = new CancellationTokenSource();
     _lastCheck        = DateTime.Now;
     _messagePublisher = messagePublisher;
     _realtimeservice  = rtservice;
 }
Ejemplo n.º 7
0
 public CyclicRunner(ITimerService timerService, IRunTarget target)
 {
     _timerService = timerService;
     _notificationReporter = target.Reporter;
     _target = target;
     _timerService.Elapsed += (sender, args) => Run();
 }
 public CryptoConnectionListener(ISerializer <TMessage> serializer, IThreadManager threadManager, ILinkNegotiator linkNegotiator, ITimerService timerService)
 {
     this.timerService   = Guard.IsNull(() => timerService);
     this.serializer     = Guard.IsNull(() => serializer);
     this.threadManager  = Guard.IsNull(() => threadManager);
     this.linkNegotiator = Guard.IsNull(() => linkNegotiator);
 }
Ejemplo n.º 9
0
 /// <summary>
 /// removes a service from the timer
 /// </summary>
 /// <param name="service">service not to be executed regularly anymore</param>
 public void RemoveService(ITimerService service)
 {
     lock (timerlock) {
         services.Remove(service);
         intervaltable.RemoveAll(e => e.Service == service);
     }
 }
Ejemplo n.º 10
0
        public HomeViewModel(IDeviceService deviceService, IShareService shareService, ISettings settings,
                             ILocationService locationService, IMvxMessenger messenger, ISendPositionService sendPositionService, IPopupService popupService, ITimerService timer)
        {
            _deviceService       = deviceService;
            _shareService        = shareService;
            _settings            = settings;
            _locationService     = locationService;
            _messenger           = messenger;
            _sendPositionService = sendPositionService;
            _popupService        = popupService;
            _timer = timer;

            Title         = "TrackMe";
            PossibleTimes = new PossibleTimeProvider().GetPossibleTimes().ToObservable();
            SelectedTime  = new PossibleTime(240);

            _deviceService.LocationStatusChanged += (sender, args) =>
            {
                GpsStatus = args.Status;

                if (!_locationService.IsWatching && args.Status == LocationStatus.Started)
                {
                    _locationService.StartWatching();
                }
            };
            GpsStatus                  = _deviceService.LocationStatus;
            _locationMessageToken      = _messenger.Subscribe <LocationMessage>(GotLocation);
            _requestStartTrackingToken = _messenger.Subscribe <RequestStartTrackingMessage>(OnRequestStartTracking);
            _messenger.Subscribe <CloseAppMessage>(message =>
            {
                _messenger.Publish(new StopTrackingMessage(this, true, Token, PrivateToken, _timeEnd));
            });

            TrackConnectionStatus();
        }
Ejemplo n.º 11
0
        public HealthService(
            ControllerOptions controllerOptions,
            IPi2GpioService pi2GpioService,
            ITimerService timerService,
            ISystemInformationService systemInformationService)
        {
            if (controllerOptions == null)
            {
                throw new ArgumentNullException(nameof(controllerOptions));
            }
            if (timerService == null)
            {
                throw new ArgumentNullException(nameof(timerService));
            }
            if (systemInformationService == null)
            {
                throw new ArgumentNullException(nameof(systemInformationService));
            }

            _systemInformationService = systemInformationService;

            if (controllerOptions.StatusLedNumber.HasValue)
            {
                _led = pi2GpioService.GetOutput(controllerOptions.StatusLedNumber.Value);
                _ledTimeout.Start(TimeSpan.FromMilliseconds(1));
            }

            timerService.Tick += Tick;
        }
Ejemplo n.º 12
0
        public void OnGameModeInit(IWorldService worldService, IEntityManager entityManager,
                                   INativeObjectProxyFactory proxyFactory, ITimerService timerService)
        {
            // Only test FastNative performance if FastNative is not activated
            if (proxyFactory is FastNativeBasedNativeObjectProxyFactory)
            {
                return;
            }

            // Benchmarking
            var fastFactory = new FastNativeBasedNativeObjectProxyFactory(_client);
            var fastProxy   = (TestingFastNative)fastFactory.CreateInstance(typeof(TestingFastNative));

            _fastProxy = fastProxy;
            _nativeGetVehicleParamsEx = Interop.FastNativeFind("GetVehicleParamsEx");
            _testVehicleId            = worldService.CreateVehicle(VehicleModelType.BMX, Vector3.One, 0, 0, 0).Entity.Handle;
            //timerService.Start(_ => BenchmarkRunTimer(), TimeSpan.FromSeconds(2));
            //timerService.Start(_ => BenchmarkRunTimerProxy(), TimeSpan.FromSeconds(2));

            // Test native features
            Console.WriteLine("TEST WITH HANDLE FACTORY:");
            RunTests(proxyFactory);
            Console.WriteLine("TEST WITH FAST FACTORY:");
            RunTests(fastFactory);

            // Threading test
            // timerService.Start(_ => ThreadingTest(fastProxy, handleProxy), TimeSpan.FromSeconds(15));

            // Multiple calls test
            InvokeVehicleNatives(entityManager, fastProxy);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            ServiceHost hostTimerService = new ServiceHost(typeof(TimerService), new Uri("http://localhost:8080/TimerService"));
            ServiceHost hostTimerClient  = new ServiceHost(typeof(TimerClient), new Uri("http://localhost:8080/TimerClient"));
            ChannelFactory <ITimerService> proxyFactory = null;

            try
            {
                // start the services
                hostTimerService.Open();
                hostTimerClient.Open();

                // subscribe to ITimerService
                proxyFactory = new ChannelFactory <ITimerService>(new BasicHttpBinding(), "http://localhost:8080/TimerService");
                ITimerService timerService = proxyFactory.CreateChannel();
                timerService.Subscribe("http://localhost:8080/TimerClient");
                ((ICommunicationObject)timerService).Close();

                // wait for call backs...
                Console.WriteLine("Wait for Elapsed updates. Press enter to exit.");
                Console.ReadLine();
            }
            finally
            {
                hostTimerService.Close();
                hostTimerClient.Close();
                proxyFactory.Close();
            }
        }
        public StoreroomConfiguration(
            IAreaService areaService,
            SynonymService synonymService,
            IDeviceService deviceService,
            CCToolsBoardService ccToolsBoardService,
            ITimerService timerService,
            ITwitterClientService twitterClientService,
            AutomationFactory automationFactory,
            ActuatorFactory actuatorFactory,
            SensorFactory sensorFactory)
        {
            if (areaService == null) throw new ArgumentNullException(nameof(areaService));
            if (synonymService == null) throw new ArgumentNullException(nameof(synonymService));
            if (deviceService == null) throw new ArgumentNullException(nameof(deviceService));
            if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService));
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));
            if (twitterClientService == null) throw new ArgumentNullException(nameof(twitterClientService));
            if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory));
            if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory));
            if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory));

            _areaService = areaService;
            _synonymService = synonymService;
            _deviceService = deviceService;
            _ccToolsBoardService = ccToolsBoardService;
            _timerService = timerService;
            _twitterClientService = twitterClientService;
            _automationFactory = automationFactory;
            _actuatorFactory = actuatorFactory;
            _sensorFactory = sensorFactory;
        }
Ejemplo n.º 15
0
 public AppService(IProductService productService, ICampaignService campaignService, ITimerService timerService, IAppTimeService appTimeService)
 {
     _productService  = productService;
     _campaignService = campaignService;
     _timerService    = timerService;
     _appTimeService  = appTimeService;
 }
Ejemplo n.º 16
0
        private void ReplaceValidHumanSkill(InputEntity entity, bool isValid, InputHumanSkillState skill)
        {
            int code = 0;

            if (skill != null)
            {
                code = skill.SkillCode;
            }

            if (!isValid)
            {
                isValid = JudgeLength(code);
            }

            if (!isValid)
            {
                code = _contexts.service
                       .gameServiceSkillCodeService.SkillCodeService
                       .GetCurrentSkillCode(entity.gameInputButton.InputButton, code);
            }

            if (isValid)
            {
                ITimerService timerService = _contexts.service.gameServiceTimerService.TimerService;
                timerService.StopTimer(timerService.GeTimer(TimerId.JUDGE_SKILL_TIMER), false);
            }

            _contexts.input.ReplaceGameInputHumanSkillState(isValid, code);
        }
        private void Timer_Tick(ITimerService obj)
        {
            var timeService = ServiceLocator.Current.GetInstance <ITimeService>();
            var timePassed  = timeService.Now - _start;

            Milliseconds = Math.Round(timePassed.TotalMilliseconds / 100) * 100; // round the number of ms to the nearest 100ms
        }
Ejemplo n.º 18
0
        public TestButtonFactory(ITimerService timerService, ISettingsService settingsService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));

            _timerService = timerService;
            _settingsService = settingsService;
        }
Ejemplo n.º 19
0
        public RollerShutter(
            ComponentId id, 
            IRollerShutterEndpoint endpoint,
            ITimerService timerService,
            ISchedulerService schedulerService,
            ISettingsService settingsService)
            : base(id)
        {
            if (id == null) throw new ArgumentNullException(nameof(id));
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService));
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            _endpoint = endpoint;
            _schedulerService = schedulerService;

            settingsService.CreateSettingsMonitor<RollerShutterSettings>(Id, s => Settings = s);

            timerService.Tick += (s, e) => UpdatePosition(e);

            _startMoveUpAction = new Action(() => SetState(RollerShutterStateId.MovingUp));
            _turnOffAction = new Action(() => SetState(RollerShutterStateId.Off));
            _startMoveDownAction = new Action(() => SetState(RollerShutterStateId.MovingDown));

            endpoint.Stop(HardwareParameter.ForceUpdateState);
        }
Ejemplo n.º 20
0
        public Button(string id, IButtonAdapter adapter, ITimerService timerService, ISettingsService settingsService, IMessageBrokerService messageBroker, ILogService logService)
            : base(id)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter));
            }
            if (settingsService == null)
            {
                throw new ArgumentNullException(nameof(settingsService));
            }
            _messageBroker = messageBroker ?? throw new ArgumentNullException(nameof(messageBroker));

            _log = logService?.CreatePublisher(id) ?? throw new ArgumentNullException(nameof(logService));
            settingsService.CreateSettingsMonitor <ButtonSettings>(this, s => Settings = s.NewSettings);

            _pressedLongTimeout          = new Timeout(timerService);
            _pressedLongTimeout.Elapsed += (s, e) =>
            {
                _messageBroker.Publish(Id, new ButtonPressedLongEvent());
            };

            adapter.StateChanged += UpdateState;

            _commandExecutor.Register <ResetCommand>();
            _commandExecutor.Register <PressCommand>(c => PressInternal(c.Duration));
        }
Ejemplo n.º 21
0
        public RollerShutter(
            string id,
            IRollerShutterAdapter adapter,
            ITimerService timerService,
            ISettingsService settingsService)
            : base(id)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }

            _adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));

            _autoOffTimeout          = new Timeout(timerService);
            _autoOffTimeout.Elapsed += (s, e) => Stop();

            timerService.Tick += (s, e) => TrackPosition(e);

            settingsService.CreateSettingsMonitor <RollerShutterSettings>(this, s => Settings = s.NewSettings);

            _commandExecutor.Register <MoveUpCommand>(c => MoveUp());
            _commandExecutor.Register <MoveDownCommand>(c => MoveDown());
            _commandExecutor.Register <TurnOffCommand>(c => Stop());
            _commandExecutor.Register <ResetCommand>(c => MoveUp(true));
        }
        public TimerServiceTestsFixture()
        {
            TestTimeout                     = TimeSpan.FromSeconds(10);
            Now                             = DateTime.UtcNow;
            DateTimeService                 = new Mock <IDateTimeService>();
            DelayTaskCompletionSource       = new TaskCompletionSource <object>();
            DelayCancellationTokenSource    = new CancellationTokenSource(TestTimeout);
            Delay                           = new Mock <Func <TimeSpan, CancellationToken, Task> >();
            CallbackTaskCompletionSource    = new TaskCompletionSource <object>();
            CallbackCancellationTokenSource = new CancellationTokenSource(TestTimeout);
            SuccessCallback                 = new Mock <Func <DateTime, CancellationToken, Task> >();
            ErrorCallback                   = new Mock <Action <Exception> >();
            Interval                        = TimeSpan.Zero;
            Exception                       = new Exception();

            DateTimeService.Setup(d => d.UtcNow).Returns(Now);
            DelayCancellationTokenSource.Token.Register(() => DelayTaskCompletionSource.TrySetCanceled());
            CallbackCancellationTokenSource.Token.Register(() => CallbackTaskCompletionSource.TrySetCanceled());

            Delay.Setup(d => d(It.IsAny <TimeSpan>(), It.IsAny <CancellationToken>())).Returns <TimeSpan, CancellationToken>((d, c) =>
            {
                TimerServiceCancellationToken = c;
                DelayTaskCompletionSource.TrySetResult(null);

                return(Task.Delay(d, c));
            });

            TimerService = new TimerService(DateTimeService.Object, Delay.Object);
        }
Ejemplo n.º 23
0
 public CyclicRunner(ITimerService timerService, IRunTarget target)
 {
     _timerService         = timerService;
     _notificationReporter = target.Reporter;
     _target = target;
     _timerService.Elapsed += (sender, args) => Run();
 }
Ejemplo n.º 24
0
        public MainViewModel(IRegistryService registryService,
                             IDriveInfoService driveInfoService,
                             IDriveDetectionService detectionService,
                             IWidgetsService widgetsService,
                             ITimerService timerService,
                             IDictionary <string, IDriveViewModel> drives,
                             IDictionary <string, IInfoViewModel> widgets,
                             ILogger logger)
        {
            this.registryService  = registryService;
            this.driveInfoService = driveInfoService;
            this.widgetsService   = widgetsService;
            this.Drives           = drives;
            this.Widgets          = widgets;

            detectionService.DeviceAdded   += this.DeviceAdded;
            detectionService.DeviceRemoved += this.DeviceRemoved;

            timerService.Tick += this.TimerTick;

            this.InitRelay();

            this.Initialize();

            this.InitializeWidgets();

            this.CheckIfVersionChanged();
            logger.LogInformation(nameof(zDrive) + " is started.");
        }
        public LogicalBinaryStateActuator(ComponentId id, ITimerService timerService)
            : base(id)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));

            _timerService = timerService;
        }
Ejemplo n.º 26
0
        public MuteService(DiscordSocketClient client, DataService data, ITimerService timer)
        {
            _data   = data;
            _client = client;

            timer.AddCallback(CheckMutesAsync);
        }
Ejemplo n.º 27
0
 public DefaultOperationLogService(EntityApp app, LogLevel logLevel = Services.LogLevel.Details)
 {
     LogLevel = logLevel;
       _timerService = app.GetService<ITimerService>();
       _timerService.Elapsed1Second += TimerService_Elapsed1Second;
       app.AppEvents.FlushRequested += Events_FlushRequested;
 }
Ejemplo n.º 28
0
 public TimersController(ILogger <TimersController> logger, ITimerService timerService, IHttpContextAccessor httpContextAccessor, IMapper mapper)
 {
     _logger              = logger;
     _timerService        = timerService;
     _httpContextAccessor = httpContextAccessor;
     _mapper              = mapper;
 }
Ejemplo n.º 29
0
 public WorkSpaceViewModel(IMessenger messenger, ISelectDirectoryService selectDirectoryService, IWorkspaceStorageService workspaceStorageService, IAssignmentFileService assignmentFileService, IDirectoryService directoryService, ILanguageService languageService, IPinCodeStorageService pinCodeStorageService, IBackupService backupService, ISafePathService safePathService, IPinCodeValidator pinCodeValidator, ITimerService examStartsTimer, IDirectoryAccessValidator directoryAccessValidator, ITimerService lockUiOnInvalidPinCodeTimerService, IBoardingPassStorageService boardingPassStorageService, ITimerService assignmentFilesRedownloadTimerService, ILoggerService loggerService)
 {
     this._messenger = messenger;
     this._selectDirectoryService                          = selectDirectoryService;
     this._workspaceStorageService                         = workspaceStorageService;
     this._assignmentFileService                           = assignmentFileService;
     this._directoryService                                = directoryService;
     this._languageService                                 = languageService;
     this._pinCodeStorageService                           = pinCodeStorageService;
     this._backupService                                   = backupService;
     this._safePathService                                 = safePathService;
     this._pinCodeValidator                                = pinCodeValidator;
     this._examStartsTimer                                 = examStartsTimer;
     this._directoryAccessValidator                        = directoryAccessValidator;
     this._lockUiOnInvalidPinCodeTimerService              = lockUiOnInvalidPinCodeTimerService;
     this._boardingPassStorageService                      = boardingPassStorageService;
     this._assignmentFilesRedownloadTimerService           = assignmentFilesRedownloadTimerService;
     this._loggerService                                   = loggerService;
     this._examStartsTimer.AutoReset                       = false;
     this._examStartsTimer.Elapsed                        += (ElapsedEventHandler)((sender, args) => this.ExamHasStarted());
     this._assignmentFilesRedownloadTimerService.AutoReset = false;
     this._assignmentFilesRedownloadTimerService.Elapsed  += new ElapsedEventHandler(this.AssignmentFilesRedownloadTimerService_Elapsed);
     this._assignmentFilesRedownloadTimerService.Interval  = 600000.0;
     this.SetWorkspacePathCommand                          = (ICommand) new RelayCommand((Action <object>)(c => this.SetWorkspaceClick()), (Predicate <object>)null);
     this.ShowUnlockAssignmentFilesCommand                 = (ICommand) new RelayCommand((Action <object>)(c => this.ShowUnlockAssignmentFilesClick()), (Predicate <object>)null);
     this.UpdateLanguage((OnLanguageChanged)null);
     messenger.Register <OnLanguageChanged>((object)this, new Action <OnLanguageChanged>(this.UpdateLanguage));
     messenger.Register <OnTimeLeftUntilExamStarts>((object)this, new Action <OnTimeLeftUntilExamStarts>(this.OnTimeLeftUntilExamStarts));
     messenger.Register <OnExaminationDataLoaded>((object)this, new Action <OnExaminationDataLoaded>(this.OnExaminationDataLoaded));
     messenger.Register <OnPinCodeLoginSuccessful>((object)this, new Action <OnPinCodeLoginSuccessful>(this.OnPinCodeLoginSuccessful));
     messenger.Register <OnPinCodeLoginForceContinue>((object)this, new Action <OnPinCodeLoginForceContinue>(this.OnPinCodeLoginForceContinue));
     messenger.Register <OnExaminationUrlLoaded>((object)this, new Action <OnExaminationUrlLoaded>(this.OnExaminationUrlLoaded));
 }
Ejemplo n.º 30
0
 private void InitTimerService()
 {
     if (_timerService == null)
     {
         _timerService = Contexts.sharedInstance.service.gameServiceTimerService.TimerService;
     }
 }
Ejemplo n.º 31
0
        public Button(ComponentId id, IButtonEndpoint endpoint, ITimerService timerService, ISettingsService settingsService)
            : base(id)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (settingsService == null)
            {
                throw new ArgumentNullException(nameof(settingsService));
            }

            settingsService.CreateSettingsMonitor <ButtonSettings>(Id, s => Settings = s);

            SetState(ButtonStateId.Released);

            timerService.Tick += CheckForTimeout;

            endpoint.Pressed  += (s, e) => HandleInputStateChanged(ButtonStateId.Pressed);
            endpoint.Released += (s, e) => HandleInputStateChanged(ButtonStateId.Released);
        }
Ejemplo n.º 32
0
        public LampStateMachine(IMessageService messageService, ITimeService timeService = null, LampState initialState = LampState.Off, ITimerService timer = null)
            : base(initialState)
        {
            this.timeService = timeService ?? new TimeService();
            this.timer       = timer ?? new TimerService();

            timer.Elapsed += (s, a) => this.Fire(LampTrigger.ElapsedTime);

            this.Configure(LampState.Off)
            // .Permit(LampTrigger.PushUp, LampState.On)
            .PermitIf(LampTrigger.PushUp, LampState.On, () => IsOverTime, $"Limit > {TimeLimit}")
            .IgnoreIf(LampTrigger.PushUp, () => !IsOverTime, $"Limit <= {TimeLimit}")
            .Ignore(LampTrigger.PushDown)
            .OnEntry(() => messageService.Send("Dziękujemy za wyłączenie światła"), nameof(messageService.Send));

            this.Configure(LampState.On)
            .OnEntry(() => messageService.Send("Pamiętaj o wyłączeniu światła!"), nameof(messageService.Send))
            .OnEntry(() => timer.Start(), "Start timer")
            .Permit(LampTrigger.PushDown, LampState.Off)
            .PermitIf(LampTrigger.PushUp, LampState.Red, () => !IsOverLimit)
            .PermitIf(LampTrigger.PushUp, LampState.Off, () => IsOverLimit)
            .Permit(LampTrigger.ElapsedTime, LampState.Off)
            .OnExit(() => timer.Stop());


            this.Configure(LampState.Red)
            .OnEntry(() => redCounter++)
            .Permit(LampTrigger.PushUp, LampState.On)
            .Permit(LampTrigger.PushDown, LampState.Off);


            this.OnTransitioned(t => Console.WriteLine($"{t.Source} -> {t.Destination}"));
            this.timer = timer;
        }
Ejemplo n.º 33
0
        public TestRollerShutter(ComponentId id, TestRollerShutterEndpoint endpoint, ITimerService timerService, ISchedulerService schedulerService, ISettingsService settingsService)
            : base(id, endpoint, timerService, schedulerService, settingsService)
        {
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));

            Endpoint = endpoint;
        }
Ejemplo n.º 34
0
        public PomodoroControlService(IStorageService storageService)
        {
            FinishedWitoutSessionBreak = 0;
            TimerService   = new TimerService();
            StorageService = storageService;
            TimerService.TimerComplatedEvent += OnTimerCompleted;

            var lastState = StorageService.GetLastState();

            // check if last state is valid
            if (IsPomodoroStatusValid(lastState))
            {
                PomodoroStatus = lastState;
            }
            else
            {
                PomodoroStatus = new PomdoroStatus
                {
                    PomodoroState = PomodoroState.Ready,
                    TimerState    = TimerState.Stoped,
                };
            }

            if (PomodoroStatus != null)
            {
                TimerService.StartTime     = PomodoroStatus.StartTime;
                TimerService.RunningTime   = PomodoroStatus.RunTime;
                TimerService.RemainingTime = PomodoroStatus.RemainingTime;
                TimerService.TimerState    = PomodoroStatus.TimerState;
            }
        }
Ejemplo n.º 35
0
        public GameWindowViewModel(MainWindowViewModel main)
        {
            Main = main;
            var puzzle = Puzzle.FromRowStrings(
                "xxxxx",
                "x...x",
                "x...x",
                "x...x",
                "xxxxx"
                );
            var facade = new PiCrossFacade();

            //timer
            var timeService = ServiceLocator.Current.GetInstance <ITimeService>();

            _start = timeService.Now;

            _timer       = ServiceLocator.Current.GetInstance <ITimerService>();
            _timer.Tick += Timer_Tick;
            _timer.Start(new TimeSpan(0, 0, 0, 0, 100));

            PlayablePuzzle  = facade.CreatePlayablePuzzle(puzzle);
            SquareGrid      = Grid.Create <SquareViewModel>(PlayablePuzzle.Grid.Size, p => new SquareViewModel(PlayablePuzzle.Grid[p]));
            Timer           = "00:00:00";
            CloseGameWindow = new CloseGameWindowCommand(main);
            IsSolved        = new IsSolvedCommand(this);
        }
Ejemplo n.º 36
0
        public TimedAction(TimeSpan dueTime, TimeSpan interval, ITimerService timerService)
        {
            _timeout = dueTime;
            _interval = interval;

            _timerService = timerService;
            _timerService.Tick += CheckForTimeout;
        }
Ejemplo n.º 37
0
 public TimerController(IHubContext <TimerHub, ITimerHub> timerHub,
                        ITimerService timerService,
                        UserManager <AppUser> userManager)
 {
     _timerHub     = timerHub;
     _timerService = timerService;
     _userManager  = userManager;
 }
Ejemplo n.º 38
0
 public HeartbeatService(IFlexClient flexClient, IDateTimeService dateTimeService, IMessenger messenger, ITimerService heartbeatIntervalTimer)
 {
     this._flexClient                      = flexClient;
     this._dateTimeService                 = dateTimeService;
     this._messenger                       = messenger;
     this._heartbeatIntervalTimer          = heartbeatIntervalTimer;
     this._heartbeatIntervalTimer.Interval = 5000.0;
 }
        public TestRollerShutterFactory(ITimerService timerService, ISchedulerService schedulerService, ISettingsService settingsService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));
            if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService));

            _timerService = timerService;
            _schedulerService = schedulerService;
            _settingsService = settingsService;
        }
Ejemplo n.º 40
0
 public void Init(EntityApp app)
 {
     _app = app;
       _errorLog = _app.GetService<IErrorLogService>();
       _operationLog = _app.GetService<IOperationLogService>();
       _timerService = _app.GetService<ITimerService>();
       _timerService.Elapsed1Second += TimerService_Elapsed1Second;
       _app.AppEvents.FlushRequested += Events_FlushRequested;
 }
        public CatLitterBoxTwitterSender(ITimerService timerService, ITwitterClientService twitterClientService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));
            if (twitterClientService == null) throw new ArgumentNullException(nameof(twitterClientService));

            _twitterClientService = twitterClientService;

            timerService.Tick += Tick;
        }
Ejemplo n.º 42
0
        public SchedulerService(ITimerService timerService, IDateTimeService dateTimeService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));
            if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService));

            _timerService = timerService;
            _dateTimeService = dateTimeService;

            _timer = new Timer(e => ExecuteSchedules(), null, -1, Timeout.Infinite);
        }
Ejemplo n.º 43
0
 public Topic(
     string id, 
     IActorSystem system, 
     ITimerService timers, 
     IReminderService reminders, 
     ITopicStorage storage)
     : base(id, system)
 {
     this.timers = timers;
     this.reminders = reminders;
     this.storage = storage;
 }
Ejemplo n.º 44
0
        public Button(ComponentId id, IButtonEndpoint endpoint, ITimerService timerService, ISettingsService settingsService)
            : base(id)
        {
            if (id == null) throw new ArgumentNullException(nameof(id));
            if (endpoint == null) throw new ArgumentNullException(nameof(endpoint));
            if (settingsService == null) throw new ArgumentNullException(nameof(settingsService));

            settingsService.CreateSettingsMonitor<ButtonSettings>(Id, s => Settings = s);

            SetState(ButtonStateId.Released);

            timerService.Tick += CheckForTimeout;

            endpoint.Pressed += (s, e) => HandleInputStateChanged(ButtonStateId.Pressed);
            endpoint.Released += (s, e) => HandleInputStateChanged(ButtonStateId.Released);
        }
Ejemplo n.º 45
0
        public HealthService(
            ControllerOptions controllerOptions, 
            IPi2GpioService pi2GpioService,
            ITimerService timerService, 
            ISystemInformationService systemInformationService)
        {
            if (controllerOptions == null) throw new ArgumentNullException(nameof(controllerOptions));
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));
            if (systemInformationService == null) throw new ArgumentNullException(nameof(systemInformationService));

            _systemInformationService = systemInformationService;

            if (controllerOptions.StatusLedNumber.HasValue)
            {
                _led = pi2GpioService.GetOutput(controllerOptions.StatusLedNumber.Value);
                _ledTimeout.Start(TimeSpan.FromMilliseconds(1));
            }

            timerService.Tick += Tick;
        }
Ejemplo n.º 46
0
        public GuiService()
        {
            _graphics = ServiceLocator.Instance.GetService<GraphicsDevice>();
            _timer = ServiceLocator.Instance.GetService<ITimerService>();
            _keyboard = ServiceLocator.Instance.GetService<IKeyboardService>();
            _mouse = ServiceLocator.Instance.GetService<IMouseService>();
            _renderInterface = new Gui.LibRocketRenderInterface(_graphics, ServiceLocator.Instance.GetService<ContentManager>(), true);
            _coroutines = ServiceLocator.Instance.GetService<ICoroutineService>();

            LibRocketNet.Core.SystemInterface = new Gui.LibRocketSystemInterface(_timer);
            LibRocketNet.Core.RenderInterface = _renderInterface;
            LibRocketNet.Core.Initialize();
            LibRocketNet.Core.ScriptEvent += (o, e) =>
            {
                Console.WriteLine("[Gui] Script event:" + e.Script);
            };

            Context = LibRocketNet.Core.CreateContext(
                ContextName,
                new Vector2i(_graphics.Viewport.Width, _graphics.Viewport.Height));

            LoadFonts();
            LibRocketNet.Core.InitDebugger(Context);

            _keyboard.KeyDown += KeyDownHandler;
            _keyboard.KeyUp += KeyUpHandler;
            _mouse.ButtonDown += (o, e) => {
                Context.ProcessMouseButtonDown(e, GetKeyModifiers());
            };
            _mouse.ButtonUp +=
                (o, e) => Context.ProcessMouseButtonUp(e, GetKeyModifiers());

            _mouse.WheelChanged += (w) =>
            {
                Context.ProcessMouseWheel(-w, GetKeyModifiers());
            };
            _mouse.Move += ProcessMouseMove;

            _coroutines.StartCoroutine(UpdateUI());
        }
Ejemplo n.º 47
0
 protected override void EstablishContext()
 {
     base.EstablishContext();
     CyclicInvoker = new TimerService();
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            shipThrustOff = Game.Content.Load<Texture2D>(@"Sprites\ShipNoThrust");
            shipThrustOn = Game.Content.Load<Texture2D>(@"Sprites\ShipThrust");
            fuel = MAX_FUEL;
            fuelTimerId = Guid.NewGuid();
            base.sprite = shipThrustOff;
            base.position = new Vector2((Game as MainGame).Center.X, 100);
            base.velocity = Vector2.Zero;
            base.direction = MathHelper.Pi + MathHelper.PiOver2;
            base.spriteRotation = MathHelper.Pi;
            previousKeyState = Keyboard.GetState();

            //setup timers for the ship
            timerService = Game.Services.GetService(typeof(ITimerService)) as ITimerService;
            timerService.SetTimer(fuelTimerId, FUEL_TIME_EVENT);
        }
Ejemplo n.º 49
0
 public Topic()
 {
     timers = new TimerService(this);
     reminders = new ReminderService(this);
     storage = ServiceLocator.TopicStorage;
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Dependency injection
 /// </summary>
 /// <param name="socket"></param>
 public HttpSocket(ISocket socket, ITimerService timerService, IDns dns)
 {
     this._socket = socket;
     this._timerService = timerService;
     this._dns = dns;
 }
Ejemplo n.º 51
0
 public WeaponSystem()
     : base(Aspect.All(typeof(WeaponComponent)))
 {
     _timer = ServiceLocator.Instance.GetService<ITimerService>();
 }
Ejemplo n.º 52
0
 public HubBuffer()
 {
     timers = new TimerService(this);
 }
 public DirectionAnimation(ITimerService timerService)
     : base(timerService)
 {
 }
Ejemplo n.º 54
0
 internal StatusService(ITimerService timer)
 {
     _timer = timer;
     LifeTime = TimeSpan.FromSeconds(15);
     _timer.Elapsed += TimerElapsed;
 }
Ejemplo n.º 55
0
 private static void WriteTicks(int timer, int tickSoFar, int totalTicks, ITimerService timerService)
 {
     Console.WriteLine("Timer {0}: {1}/{2}", timer, tickSoFar, totalTicks);
     if (tickSoFar >= totalTicks)
         timerService.Stop(timer);
 }
Ejemplo n.º 56
0
        public Animation(ITimerService timerService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));

            _timerService = timerService;
        }
Ejemplo n.º 57
0
 public LibRocketSystemInterface(ITimerService timer)
 {
     _timer = timer;
 }
Ejemplo n.º 58
0
 public CoroutineSystem()
     : base(Aspect.All(typeof(CoroutineComponent)))
 {
     _timer = ServiceLocator.Instance.GetService<ITimerService>();
 }
Ejemplo n.º 59
0
 public Publisher()
 {
     timers = new TimerService(this);
 }
Ejemplo n.º 60
0
        public Pi2GpioService(ITimerService timerService)
        {
            if (timerService == null) throw new ArgumentNullException(nameof(timerService));

            timerService.Tick += (s, e) => PollOpenInputPorts();
        }