コード例 #1
0
        public FloatViewSliderSwitch(SwitchScenarioModel model) : this()
        {
            BindingContext = _model = model;

            var diff = model.Max - model.Min;

            _round = (int)(2 / diff);

            //binding works incorrectly
            slider.Maximum = model.Max; //crutch
            slider.Minimum = model.Min; //crutch

            slider.Value         = double.Parse(model.ScenarioValue);
            _tempValue           = _tempValue_current = model.ScenarioValue;
            _iteration           = (model.Max - model.Min) / 20;
            slider.ValueChanged += (o, e) =>
            {
                var value = slider.Value;
                value      = Math.Round(value, _round);
                _tempValue = value.ToString();
            };
            _tokenSource = SystemUtils.StartTimer(
                (token) =>
            {
                if (_tempValue != _tempValue_current)
                {
                    model.ScenarioValue = _tempValue_current = _tempValue;
                }
            },
                () => FloatView_ValueUpdateInterval);
            SizeChanged += (o, e) =>
            {
                HeightRequest = Width * 2;
            };
        }
コード例 #2
0
        private void ReInitTimer()
        {
            _timerCancellationToken?.Cancel();

            _timerCancellationToken = SystemUtils.StartTimer(
                (token) => _manager.RefreshIteration(),
                () => {
                var interval = SleepInterval_Normal;
                try
                {
                    if (IsPhoneSleeping)
                    {
                        interval = SleepInterval_ScreenOff;
                    }
                    else if (IsPhoneInPowerSave)
                    {
                        interval = SleepInterval_PowerSaving;
                    }
                }
                catch
                {
                    //do nothing
                }
                return(interval);
            },
                false);
        }
コード例 #3
0
 public void StartListenChanges()
 {
     _listenersCancellationTokenSource?.Cancel();
     _listenersCancellationTokenSource =
         SystemUtils.StartTimer(
             (token) => RefreshIteration(),
             () => _succeed ? ScenariosManagerListenInterval : ScenariosManagerListenInterval_onError);
 }
コード例 #4
0
        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);
        }
コード例 #5
0
        public static void Start()
        {
            var launcherAssembly    = typeof(LazuriteUI.Windows.Launcher.App).Assembly;
            var launcherExePath     = Path.GetFullPath(Lazurite.Windows.Utils.Utils.GetAssemblyPath(launcherAssembly));
            var launcherProcessName = Path.GetFileNameWithoutExtension(launcherExePath);

            var currentProcess         = Process.GetCurrentProcess();
            var currentProcessName     = currentProcess.ProcessName;
            var currentProcessLocation = GetProcessFilePath(currentProcess);
            var currentProcessId       = currentProcess.Id;

            var listenInterval = DuplicatedProcessesListenerInterval;

            var action = (Action)(() =>
            {
                try
                {
                    var processes =
                        Process.GetProcessesByName(currentProcessName)
                        .Union(Process.GetProcessesByName(launcherProcessName))
                        .ToArray();
                    var targetProcesses = processes.Where(x =>
                                                          x.Id != currentProcessId &&
                                                          ((StringComparer.OrdinalIgnoreCase.Equals(x.ProcessName, launcherProcessName) &&
                                                            StringComparer.OrdinalIgnoreCase.Equals(GetProcessFilePath(x), launcherExePath)) ||
                                                           (StringComparer.OrdinalIgnoreCase.Equals(x.ProcessName, currentProcessName) &&
                                                            StringComparer.OrdinalIgnoreCase.Equals(GetProcessFilePath(x), currentProcessLocation))))
                                          .ToArray();
                    if (targetProcesses.Any())
                    {
                        foreach (var process in targetProcesses)
                        {
                            process.Kill();
                        }

                        Found?.Invoke(App.Current, new EventsArgs <Process[]>(targetProcesses));
                        listenInterval = DuplicatedProcessesListenerInterval_onFound;
                    }
                    else
                    {
                        listenInterval = DuplicatedProcessesListenerInterval;
                    }
                    //crutch
                    foreach (var process in processes)
                    {
                        process.Dispose();
                    }
                }
                catch (Exception e)
                {
                    Log.Warn("Ошибка во время получения процессов в DuplicatedProcessesListener. Возможной причиной может являться антивирус или отсутвие доступа.", e);
                }
            });

            SystemUtils.StartTimer((token) => action(), () => listenInterval);
        }
コード例 #6
0
        public static void DoAfter(Action action, int timeoutMs)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            SystemUtils.StartTimer((t) =>
            {
                action();
                t.Cancel();
            },
                                   () => timeoutMs,
                                   false);
        }
コード例 #7
0
        public void Initialize()
        {
            Initialize(GetScenarios());

            _updateUICancellationToken = SystemUtils.StartTimer(
                (token) => {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    foreach (var scenario in GetScenarios())
                    {
                        RefreshAndReCalculateItem(scenario);
                    }
                }));
            },
                () => UpdateUIInterval_MS);
        }
コード例 #8
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);
        }
コード例 #9
0
 private void InitializeTimer()
 {
     _timerCancellationTokenSource?.Cancel();
     _timerCancellationTokenSource = SystemUtils.StartTimer((c) => TimerTick(), () => 30000);
 }
コード例 #10
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);
            }
        }