Exemplo n.º 1
0
        /// <summary>
        /// Execute scenario in other thread
        /// </summary>
        /// <param name="param"></param>
        /// <param name="cancelToken"></param>
        public virtual void ExecuteAsyncParallel(ScenarioActionSource source, string param, ExecutionContext parentContext)
        {
            CheckRights(source, parentContext);

            TaskUtils.StartLongRunning(() =>
            {
                CheckValue(param, parentContext);
                var output = new OutputChangedDelegates();
                ExecutionContext context;
                var oldVal = GetPreviousValue();
                if (parentContext != null)
                {
                    var cancellationTokenSource = new SafeCancellationToken();
                    parentContext.CancellationTokenSource.RegisterCallback(cancellationTokenSource.Cancel);
                    context = new ExecutionContext(this, param, oldVal, output, parentContext, cancellationTokenSource);
                }
                else
                {
                    context = new ExecutionContext(this, param, oldVal, output, new SafeCancellationToken());
                }
                CheckContext(context);
                HandleExecution(() => ExecuteInternal(context));
            },
                                       HandleSet);
        }
Exemplo n.º 2
0
 public ExecutionContext(IAlgorithmContext algorithmContext, string input, string previousValue, OutputChangedDelegates output, SafeCancellationToken cancellationTokenSource)
 {
     OutputChanged           = output;
     CancellationTokenSource = cancellationTokenSource;
     AlgorithmContext        = algorithmContext;
     Input         = input;
     PreviousValue = previousValue;
 }
        public FloatViewSwitch(ScenarioModel model) : this()
        {
            DataContext = _model = model;

            var diff = model.Max - model.Min;

            _round = (int)(2 / diff);

            _tempValueToInstall = _tempValueToUpdate = model.ScenarioValue;
            lblCaption.Content  = _model.ScenarioValueWithUnit; //crutch #0

            //crutch #1
            _model.PropertyChanged += (o, e) =>
            {
                if (e.PropertyName == nameof(_model.ScenarioValue))
                {
                    if (model.ScenarioValue != _tempValueToInstall)
                    {
                        _tempValueToInstall   = model.ScenarioValue;
                        _scenarioValueChanged = true;
                    }
                }
            };

            _iteration   = (model.Max - model.Min) / 40;
            slider.Value = double.Parse(_tempValueToInstall ?? "0");

            //crutch #2
            slider.ValueChanged += (o, e) =>
            {
                var value = slider.Value;
                value = Math.Round(value, _round);

                _tempValueToUpdate    = value.ToString();
                _scenarioValueChanged = false;

                lblCaption.Content = _tempValueToUpdate + _model.Unit; //crutch #3
            };

            //crutch #4
            _tokenSource = SystemUtils.StartTimer(
                (token) =>
            {
                if (_tempValueToUpdate != _tempValueToInstall && !_scenarioValueChanged)
                {
                    model.ScenarioValue = _tempValueToInstall = _tempValueToUpdate;
                }

                if (_tempValueToInstall != _tempValueToUpdate && _scenarioValueChanged)
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        slider.Value = double.Parse(_tempValueToUpdate = _tempValueToInstall);
                    }));
                }
            },
                () => FloatView_ValueUpdateInterval);
        }
 public void Dispose()
 {
     if (_changer != null)
     {
         _changer.VolumeDown -= _changer_VolumeChanged;
         _changer.VolumeUp   -= _changer_VolumeChanged;
     }
     _tokenSource?.Cancel();
     _tokenSource = null;
 }
Exemplo n.º 5
0
 public ExecutionContext(IAlgorithmContext algorithmContext, string input, string previousValue, OutputChangedDelegates output, ExecutionContext parentContext, SafeCancellationToken cancellationTokenSource)
 {
     OutputChanged           = output;
     AlgorithmContext        = algorithmContext;
     Input                   = input;
     PreviousValue           = previousValue;
     CancellationTokenSource = cancellationTokenSource;
     ParentContext           = parentContext;
     ExecutionNesting        = ParentContext.ExecutionNesting + 1;
 }
Exemplo n.º 6
0
 public void Sleep(int ms, SafeCancellationToken cancelToken)
 {
     if (ms <= SleepCancelTokenIterationInterval || cancelToken.Equals(SafeCancellationToken.None))
     {
         Thread.Sleep(ms);
     }
     else
     {
         for (int i = 0; i <= ms && !cancelToken.IsCancellationRequested; i += SleepCancelTokenIterationInterval)
         {
             Thread.Sleep(SleepCancelTokenIterationInterval);
         }
     }
 }
Exemplo n.º 7
0
        public SafeCancellationToken StartTimer(Action <SafeCancellationToken> tick, Func <int> needInterval, bool startImmidiate = true, bool ticksSuperposition = false)
        {
            bool  canceled     = false;
            bool  executionNow = false;
            Timer timer        = null;

            var cancellationToken = new SafeCancellationToken();

            cancellationToken.RegisterCallback(() =>
            {
                if (!canceled)
                {
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
                    timer.Dispose();
                    canceled = true;
                }
            });

            var interval = needInterval?.Invoke() ?? 1000;

            timer = new Timer(
                (t) =>
            {
                if ((!executionNow || ticksSuperposition) && !cancellationToken.IsCancellationRequested)
                {
                    executionNow = true;
                    try
                    {
                        tick?.Invoke(cancellationToken);
                    }
                    finally
                    {
                        if (!canceled)
                        {
                            interval = needInterval?.Invoke() ?? 1000;
                            timer?.Change(interval, interval);
                        }
                        executionNow = false;
                    }
                }
            },
                null,
                startImmidiate ? 0 : interval,
                interval
                );

            return(cancellationToken);
        }
Exemplo n.º 8
0
        public void Initialize()
        {
            Initialize(GetScenarios());

            _updateUICancellationToken = SystemUtils.StartTimer(
                (token) =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    foreach (var scenario in GetScenarios())
                    {
                        RefreshAndReCalculateItem(scenario);
                    }
                }));
            },
                () => UpdateUIInterval_MS);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Begin execute
        /// </summary>
        public void Run()
        {
            try
            {
                if (!CancellationToken?.IsCancellationRequested ?? false)
                {
                    throw new InvalidOperationException("Невозможно запустить триггер, так как предыдущее выполнение не остановлено!");
                }

                Enabled           = true;
                CancellationToken = new SafeCancellationToken();
                RunInternal();
            }
            catch (Exception)
            {
                Log.Error($"Ошибка во время выполнения триггера [{Name}][{Id}]");
            }
        }
Exemplo n.º 10
0
        private void ReInitTimer()
        {
            _timerCancellationToken?.Cancel();
            _timerCancellationToken = SystemUtils.StartTimer(
                (token) => _manager.RefreshIteration(),
                () =>
            {
                if (_manager == null)
                {
                    return(Timeout.Infinite);
                }

                var interval = _manager.ListenerSettings.ScreenOnInterval;
                try
                {
                    if (IsPhoneSleeping)
                    {
                        interval = _manager.ListenerSettings.ScreenOffInterval;
                    }
                    else if (IsPhoneInPowerSave)
                    {
                        interval = _manager.ListenerSettings.PowerSavingModeInterval;
                    }
                    else if (_manager.ConnectionState != MainDomain.ManagerConnectionState.Connected)
                    {
                        interval = _manager.ListenerSettings.OnErrorInterval;
                    }
                }
                catch
                {
                    // Do nothing
                }
                return(interval);
            },
                false);
        }
Exemplo n.º 11
0
 private void InitializeTimer()
 {
     _timerCancellationTokenSource?.Cancel();
     _timerCancellationTokenSource = SystemUtils.StartTimer((c) => TimerTick(), () => 30000);
 }
Exemplo n.º 12
0
 protected SafeCancellationToken PrepareCancellationTokenSource() => _cancellationToken = new SafeCancellationToken();
Exemplo n.º 13
0
 public void Dispose()
 {
     _updateUICancellationToken?.Cancel();
     _updateUICancellationToken = null;
 }
Exemplo n.º 14
0
        protected override void RunInternal()
        {
            if (GetScenario() == null)
            {
                return;
            }

            //удаляем старую подписку, если имеется
            if (_lastSubscribe != null)
            {
                GetScenario().RemoveOnStateChanged(_lastSubscribe);
            }

            //выполнение по подписке на изменение значения
            var executeBySubscription = true;

            //если сценарий это одиночное действие и нельзя подписаться на изменение целевого действия
            //то не выполняем по подписке, а выполняем просто через цикл
            if (GetScenario() is SingleActionScenario singleActionScen && !singleActionScen.ActionHolder.Action.IsSupportsEvent)
            {
                executeBySubscription = false;
            }

            var contextCancellationToken = new SafeCancellationToken();

            CancellationToken.RegisterCallback(contextCancellationToken.Cancel);
            if (executeBySubscription)
            {
                _lastSubscribe = (sender, args) =>
                {
                    if (CancellationToken.IsCancellationRequested)
                    {
                        //crutch; scenario can be changed before initializing, then we need to remove
                        //current subscribe from previous scenario. CancellationToken.IsCancellationRequested
                        //can be setted in true only when trigger stopped;
                        args.Value.Scenario.RemoveOnStateChanged(_lastSubscribe);
                    }
                    else
                    {
                        if (!args.Value.OnlyIntent)
                        {
                            var action        = TargetAction;
                            var outputChanged = new OutputChangedDelegates();
                            outputChanged.Add((value) => GetScenario().SetCurrentValue(value, ExecuteActionSource));
                            contextCancellationToken.Cancel();
                            contextCancellationToken = new SafeCancellationToken();
                            var executionContext = new ExecutionContext(this, args.Value.Value, args.Value.PreviousValue, outputChanged, contextCancellationToken);
                            TaskUtils.StartLongRunning(
                                () => action.SetValue(executionContext, string.Empty),
                                (exception) => Log.ErrorFormat(exception, "Ошибка выполнения триггера [{0}][{1}]", Name, Id));
                        }
                    }
                };
                GetScenario().SetOnStateChanged(_lastSubscribe);
            }
            else
            {
                var lastVal = string.Empty;
                var timerCancellationToken = SystemUtils.StartTimer(
                    (token) =>
                {
                    try
                    {
                        var curVal = GetScenario().CalculateCurrentValue(ViewActionSource, null);
                        if (!lastVal.Equals(curVal))
                        {
                            var prevVal = GetScenario().GetPreviousValue();
                            lastVal     = curVal;
                            contextCancellationToken.Cancel();
                            contextCancellationToken = new SafeCancellationToken();
                            var executionContext     = new ExecutionContext(this, curVal, prevVal, new OutputChangedDelegates(), contextCancellationToken);
                            try
                            {
                                TargetAction.SetValue(executionContext, string.Empty);
                            }
                            catch (Exception exception)
                            {
                                Log.ErrorFormat(exception, "Ошибка выполнения триггера [{0}][{1}]", Name, Id);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat(e, "Ошибка выполнения триггера [{0}][{1}]", Name, Id);
                    }
                },
                    () => TriggerChangesListenInterval,
                    true,
                    ticksSuperposition: true /*наложение тиков*/);
                CancellationToken.RegisterCallback(timerCancellationToken.Cancel);
            }
        }
        private void StartListen()
        {
            StopListen();
            _isListening            = true;
            _timerCancellationToken = new SafeCancellationToken();
            TaskUtils.StartLongRunning(
                () =>
            {
                while (!_timerCancellationToken.IsCancellationRequested && ServerScenariosInfos.Any())
                {
                    for (var i = 0; i < ServerScenariosInfos.Count; i++)
                    {
                        if (i >= ServerScenariosInfos.Count)
                        {
                            i = 0;
                        }

                        if (!ServerScenariosInfos.Any() || _timerCancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        var info  = ServerScenariosInfos[i];
                        var error = false;

                        Log.Debug($"Remote scenario refresh iteration begin: [{info.Name}][{info.ScenarioId}]");

                        try
                        {
                            var client      = ServiceClientFactory.Current.GetClient(Credentials);
                            var newScenInfo = TaskUtils.Wait(client.GetScenarioInfo(info.ScenarioId));
                            if (!info.Unregistered)
                            {
                                info.ValueChangedCallback(new RemoteScenarioValueChangedArgs(info, newScenInfo));
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Info($"Ошибка во время соединения с удаленным сценарием. {e.Message}. Сценарий: [{info.Name}]:[{info.ScenarioId}]");
                            error = true;
                            if (!info.Unregistered)
                            {
                                info.IsAvailableChangedCallback(new RemoteScenarioAvailabilityChangedArgs(info, false));
                            }
                        }

                        Log.Debug($"Remote scenario refresh iteration end: [{info.Name}][{info.ScenarioId}]");

                        if (!ServerScenariosInfos.Any() || _timerCancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        var timeout = error ? CalculateTimeoutOnError() : CalculateTimeout();
                        SystemUtils.Sleep(timeout, _timerCancellationToken);
                    }
                }
                StopListen();
            },
                (e) => Log.Error("Ошибка во время прослушивания удаленных сценариев", e));
        }