private void CmdListenerBsSmRequest32OnDataReceived(IList <byte> bytes, IBsSmAndKsm1DataCommand32Request data) { _notifier.Notify(() => { BsSmAndKsm1RequestDataVm = data; BsSmAndKsm1RequestDataTextVm.Update(bytes); }); }
private void CmdListenerMukFlapOuterAirReply03OnDataReceived(IList <byte> bytes, IMukFlapAirReply03Telemetry data) { _notifier.Notify(() => { Reply03TelemetryText.Update(bytes); Reply03Telemetry = data; }); }
public void LoadTrendAsync(Action <OnCompleteEventArgs> onComplete) { _bworker.AddWork( () => { try { if (!IsTrendLoaded) { //var beginTime = _psnDataInformation.BeginTime.HasValue ? _psnDataInformation.BeginTime.Value : (_psnDataInformation.SaveTime.HasValue ? _psnDataInformation.SaveTime.Value : DateTime.Now); //var trend = _psnData.LoadTrend(_psnConfiguration, _signalConfiguration.Address, beginTime); var trend = _trendLoader.LoadTrend(); lock (_sync) { _points = trend; _isTrendLoaded = true; } } if (onComplete != null) { _uiNotifier.Notify(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Ok, "Тренд сигнала ПСН " + Name + " загружен"))); } } catch (Exception ex) { lock (_sync) { _points.Clear(); _isTrendLoaded = false; } if (onComplete != null) { _uiNotifier.Notify(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, "Тренд сигнала ПСН " + Name + " не был загружен, причина: " + ex))); } } }); }
private void CmdListenerMukFridgeFanReply03OnDataReceived(IList <byte> bytes, IMukCondensorFanReply03Data data) { _notifier.Notify(() => { Reply03DataText.Update(bytes); Reply03Data = data; }); }
public void LogAnalogueParameter(string parameterName, double?value) { _uiNotifier.Notify(() => { if (value.HasValue) { if (!_logs.ContainsKey(parameterName)) { var dataSeries = new XyDataSeries <DateTime, double> { SeriesName = parameterName }; var color = _colors.First(c => _usedColors.All(uc => uc != c)); _usedColors.Add(color); var renderSeries = new FastLineRenderableSeries { DataSeries = dataSeries, SeriesColor = color }; var vm = new ChartSeriesViewModel(dataSeries, renderSeries); var metadata = new SeriesAdditionalData(vm); AnalogSeries.Add(vm); AnalogSeriesAdditionalData.Add(metadata); _logs.Add(parameterName, new PointsSeriesAndAdditionalData(vm, metadata, dataSeries, renderSeries)); } _logs[parameterName].DataSeries.Append(DateTime.Now, value.Value); _updatable?.Update(); } }); }
private void Reply03ListenerOnDataReceived(IList <byte> bytes, IMukWarmFloorReply03Data data) { _notifier.Notify(() => { Reply03 = data; Reply03BytesTextVm.Update(bytes); }); }
private void CmdListenerBsSmRequest32OnDataReceived(IList <byte> bytes, IBsSmRequest32Data data) { _notifier.Notify(() => { BsSmRequest32Data = data; BsSmRequest32DataBytes.Update(bytes); }); }
private void Set() { BackgroundColor = Colors.Yellow; // TODO: check thread safety: _asyncParamSetter.Invoke(SettValue, ex => { if (ex != null) { _uiNotifier.Notify(() => BackgroundColor = Colors.OrangeRed); } else { _uiNotifier.Notify(() => BackgroundColor = Colors.LimeGreen); } }); }
public MainWindowViewModel(IThreadNotifier notifier, IWindowSystem windows) { _notifier = notifier; _windows = windows; _loader = new Loader(); _repository = _loader.GetLocalDirectoryRepository("C:\\Users\\aj01\\rpd.storage"); _locomotives = new ObservableCollection <LocomotiveViewModel>(); /* * var importRepo = _loader.GetZippedRepository("C:\\Users\\aj01\\Downloads\\Mout.rpd"); * importRepo.Open(cea => { * Console.WriteLine("Zip repo opened"); * }, pea => { }); */ _repository.Open(ea => _notifier.Notify(() => { if (ea.ResultCode == OnCompleteEventArgs.CompleteResult.Ok) { foreach (var loc in _repository.Locomotives) { _locomotives.Add(new LocomotiveViewModel(loc)); } } else { _windows.ShowMessageBox(ea.Message, "Error on repo opening"); } }), e => { Console.WriteLine(e.ProgressPercent.ToString("f2") + "%"); }); WindowTitle = "Max RPD Id = " + _loader.AvailablePsnConfigruations.Max(pc => pc.RpdId) + " TOTAL CONFIGS: " + _loader.AvailablePsnConfigruations.Count(); }
private void Set() { if (!UshortValue.HasValue) { return; } IsEnabled = false; LastOperationColor = Colors.RoyalBlue; _parameterSetter.SetParameterAsync(ParamIndex, UshortValue.Value.HighFirstUnsignedValue, exception => { _uiNotifier.Notify(() => { try { if (exception != null) { throw new Exception("Произошла ошибка во время установки параметра", exception); } // if all ok: LastOperationColor = Colors.Green; } catch (Exception ex) { // TODO: log exception to console LastOperationColor = Colors.OrangeRed; } finally { IsEnabled = true; } }); }); }
public ParameterSetterViewModelSimple(IParameterSetter parameterSetter, IThreadNotifier uiNotifier, IParameterInjectionConfiguration injectionConfiguration) { _uiNotifier = uiNotifier; CustomValueList = injectionConfiguration.PreselectedValueList; _lastSet = LastSetStateResult.Unknown; // TODO: follow https://reactiveui.net/docs/guidelines/framework/prefer-oaph-over-properties var x = this.WhenAnyValue(vm => vm.SelectedValue).Subscribe(val => Value = val.Value); _setValue = ReactiveCommand.Create(() => { Console.WriteLine($"Setting for param {injectionConfiguration.ZeroBasedParameterNumber} value " + injectionConfiguration.GetValue(_value)); parameterSetter.SetParameterAsync(injectionConfiguration.ZeroBasedParameterNumber, injectionConfiguration.GetValue(_value), ex => { _uiNotifier.Notify(() => { if (ex != null) { LastSet = LastSetStateResult.Unsuccess; } else { LastSet = LastSetStateResult.Success; } }); }); }); }
private void MetroWindow_Closed(object sender, EventArgs e) { _appMainThreadNotifier.Notify(() => { Application.Current.Shutdown(); Thread.Sleep(555); // TODO: make it proper Process.GetCurrentProcess().Kill(); }); }
private void RunTest() { TestLogLines.Clear(); LogUnsafe("Запуск теста", Colors.LimeGreen); AssociatedWithModelTest.BeginTest(() => { // TODO: test has been really started _uiNotifier.Notify(() => { IsRunningTest = true; }); }, (progress, stepResult, message) => { LogSafe(message, stepResult == TestSysStepResult.Good ? Colors.Lime : Colors.OrangeRed); } , testResult => { _uiNotifier.Notify(() => { try { switch (testResult) { case TestSysResult.Success: TestCompleteColor = Colors.Lime; break; case TestSysResult.Fail: TestCompleteColor = Colors.OrangeRed; break; case TestSysResult.Canceled: TestCompleteColor = Colors.Yellow; break; default: throw new ArgumentOutOfRangeException(nameof(testResult), testResult, null); } LogUnsafe("Тест завершен", TestCompleteColor); } catch (Exception e) { Console.WriteLine(e); LogSafe("Произошла ошибка при завершении тестирования: " + e.Message, Colors.OrangeRed); } finally { IsRunningTest = false; } }); }); }
/// <summary> /// Получает список репозиториев FTP сервера /// </summary> /// <param name="ftpHost">Адрес узла (IP-адрес или доменное имя)</param> /// <param name="ftpPort">TCP порт, на котором расположен FTP сервер</param> /// <param name="ftpUsername">Имя пользователя FTP сервера</param> /// <param name="ftpPassword">Пароль пользователя FTP сервера</param> /// <param name="callbackAction">Действие обратного вызова по получению списка репозиториев</param> public void GetFtpRepositoryInfosAsync(string ftpHost, int ftpPort, string ftpUsername, string ftpPassword, Action <OnCompleteEventArgs, IEnumerable <IFtpRepositoryInfo> > callbackAction) { _backWorker.AddWork( () => { try { var result = new List <IFtpRepositoryInfo>(); using (var conn = new FtpClient()) { conn.Host = ftpHost; conn.Port = ftpPort; conn.Credentials = new NetworkCredential(ftpUsername, ftpPassword); var items = conn.GetListing(); // list root items foreach (var ftpListItem in items) { try { if (ftpListItem.Type == FtpFileSystemObjectType.Directory) { var deviceNumber = int.Parse(ftpListItem.Name); result.Add(new FtpRepositoryInfoSimple { DeviceNumber = deviceNumber, FtpHost = ftpHost, FtpPassword = ftpPassword, FtpPort = ftpPort, FtpUsername = ftpUsername }); } } catch /*(Exception ex)*/ { continue; // FTP server can contain some other directories } } } if (callbackAction != null) { _uiNotifier.Notify(() => callbackAction(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, "Список устройств получен"), result)); } } catch (Exception ex) { if (callbackAction != null) { _uiNotifier.Notify(() => callbackAction(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, ex.ToString()), null)); } } }); }
public void ReceiveCommand(byte addr, byte code, byte[] data) { _notifier.Notify(() => { if (IsRecording) { _recordedData.Add(data); RaisePropertyChanged(() => RecordsCount); } }); }
private void CmdListenerKsmParamsOnDataReceived(IList <byte> bytes, IList <BytesPair> data) { _notifier.Notify(() => { for (int i = 0; i < _parameterVmList.Count; ++i) { _parameterVmList[i].ReceivedBytesValue = data[i]; } DataAsText.Update(bytes); }); }
private void CmdListenerBsSm32RequestDataReceived(IList <byte> bytes, IBsSmRequest32Data data) { _uiNotifier.Notify(() => { BsSmFaultVm1.Code = data.Fault1; BsSmFaultVm2.Code = data.Fault2; BsSmFaultVm3.Code = data.Fault3; BsSmFaultVm4.Code = data.Fault4; BsSmFaultVm5.Code = data.Fault5; }); }
private void ParameterModelOnNotifyDataReceived() { _uiNotifier.Notify(() => { try { DisplayValue = _displayValueGetter(_parameterModel.ReceivedRawValue); } catch { DisplayValue = _fallbackValue; } }); // TODO: many calls could lag interface! }
private void QueueBackgroundWorkerTest() { Log("QueueBackgroundWorkerTest"); var bw = new QueueBackWorker <Action>(action => action()); _queueWorker = bw; _uiNotifier = bw; for (int i = 0; i < 10; ++i) { var i1 = i; _queueWorker.AddToExecutionQueue(() => { Log("Hello" + i1); _uiNotifier.Notify(() => Log("World" + i1)); }); } }
public static void NotifyAndWait(this IThreadNotifier tn, Action notifyAction) { var signal = new AutoResetEvent(false); Exception executionExcpetion = null; tn.Notify(() => { try { notifyAction(); } catch (Exception ex) { executionExcpetion = ex; } signal.Set(); }); signal.WaitOne(); if (executionExcpetion != null) { throw new Exception("Exception during notification", executionExcpetion); } }
private void Set() { try { var valueToSend = _sendConverter.Build(FormattedValue.RawValue); IsEnabled = false; LastOperationColor = Colors.RoyalBlue; _parameterSetter.SetParameterAsync(_paramIndex, valueToSend.HighFirstUnsignedValue, exception => { _uiNotifier.Notify(() => { try { if (exception != null) { throw new Exception("Произошла ошибка во время установки параметра", exception); } LastOperationColor = Colors.Green; } catch //(Exception ex) { { // TODO: log exception to console //Console.WriteLine(ex); LastOperationColor = Colors.OrangeRed; } finally { IsEnabled = true; } }); }); } catch { LastOperationColor = Colors.IndianRed; IsEnabled = true; } }
public void Open(Action <OnCompleteEventArgs> onComplete, Action <OnProgressChangeEventArgs> onProgressChange) { _uiNotifier.Notify(() => onProgressChange(new OnProgressChangeEventArgs(0))); if (!IsOpened) { IsOpened = true; _backWorker.AddWork( () => { try { var openResult = _openStorageFunc(); _psnDataStorage = openResult.PsnDataStorage; _psnDataInformtationStorage = openResult.PsnDataInformationStorage; _psnDataCustomConfigurationsStorage = openResult.PsnDataCustomConfigurationsesStorage; _deviceInformationStorage = openResult.DeviceInformationStorage; _psnConfigurationsStorage = openResult.PsnConfigurationsStorage; InitialTreeBuildUnsafe(pp => _uiNotifier.NotifyAndWait(() => onProgressChange(new OnProgressChangeEventArgs((int)pp)))); _uiNotifier.NotifyAndWait(() => onProgressChange(new OnProgressChangeEventArgs(100))); _uiNotifier.NotifyAndWait(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Ok, "Репозиторий успешно открыт"))); } catch (Exception ex) { _uiNotifier.NotifyAndWait(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, ex.ToString()))); IsOpened = false; } }); } else { _uiNotifier.Notify(() => onProgressChange(new OnProgressChangeEventArgs(100))); _uiNotifier.Notify(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Ok, "Внимание, репозиторий уже открыт"))); } }
private void ChannelWithIoProgressOnProgressChanged(double progressPercentage) { _notifier.Notify(() => Progress = progressPercentage); }
/// <summary> /// МУК вентилятора испарителя, MODBUS адрес = 3 /// </summary> /// <param name="bytes"></param> /// <param name="data"></param> private void CmdListenerMukVaporizerReply03OnDataReceived(IList <byte> bytes, IMukFanVaporizerDataReply03 data) { _uiNotifier.Notify(() => { MukInfo3 = IsFullVersion ? new TextFormatterIntegerDotted().Format(data.FirmwareBuildNumber) : OkLinkText; MukInfoColor3 = OkLinkColor; if (data.Diagnostic1Parsed.FanControllerLinkLost) { EvaporatorFanControllerInfo = NoLinkText; EvaporatorFanControllerInfoColor = NoLinkColor; } else { EvaporatorFanControllerInfo = OkLinkText; EvaporatorFanControllerInfoColor = OkLinkColor; } if (data.TemperatureAddress1.NoLinkWithSensor) { SensorOuterAirInfo = NoSensorText; SensorOuterAirInfoColor = NoSensorColor; } else { SensorOuterAirInfo = data.TemperatureAddress1.Indication.ToString("f2"); SensorOuterAirInfoColor = OkSensorColor; } if (data.TemperatureAddress2.NoLinkWithSensor) { SensorRecycleAirInfo = NoSensorText; SensorRecycleAirInfoColor = NoSensorColor; } else { SensorRecycleAirInfo = data.TemperatureAddress2.Indication.ToString("f2"); SensorRecycleAirInfoColor = OkSensorColor; } if (data.TemperatureAddress3.NoLinkWithSensor) { SensorSupplyAirInfo = NoSensorText; SensorSupplyAirInfoColor = NoSensorColor; } else { SensorSupplyAirInfo = data.TemperatureAddress3.Indication.ToString("f2"); SensorSupplyAirInfoColor = OkSensorColor; } FanEvaporatorInfo = data.FanSpeed.ToString(CultureInfo.InvariantCulture); if (data.Diagnostic1.GetBit(4)) { FanEvaporatorColor = ErDiagColor; FanEvaporatorInfo += ", неисправность"; } else { FanEvaporatorColor = OkDiagColor; FanEvaporatorInfo += ", норма"; } CalculatedTemperatureSetting = data.CalculatedTemperatureSetting.ToString("f2"); }); }
private void BsSmCmdListenerOnDataReceived(IList <byte> bytes, IBsSmAndKsm1DataCommand32Reply data) { _notifier.Notify(() => AstroTime = data.AstronomicTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); }
public void WriteFirmware(string firmwireHexFilename, string deviceDriveLetter, Action <OnCompleteEventArgs> onComplete) { _backWorker.AddWork( () => { try { var cmdWriter = new RpdCommandWriter(deviceDriveLetter); var cmd = new CmdWriteFirmware(); cmdWriter.WriteCommandSync(cmd, 3); // wait 3 seconds after writing { var p = new Process { StartInfo = { CreateNoWindow = false, UseShellExecute = false, FileName = "batchisp", Arguments = "-device at32uc3b0256 -hardware usb -operation erase f memory flash blankcheck loadbuffer " + "\"" + firmwireHexFilename + "\"" + " program verify" } }; p.Start(); p.WaitForExit(); //processOutput = p.StandardOutput.ReadToEnd(); //if (!processOutput.Contains("Summary: Total 10 Passed 10 Failed 0")) //processResultOk = false; } //if (processResultOk) { var p = new Process { StartInfo = { CreateNoWindow = false, UseShellExecute = false, FileName = "batchisp", Arguments = "-device at32uc3b0256 -hardware usb -operation memory configuration 0xFFFFEFF8" } }; //p.StartInfo.CreateNoWindow = true; //p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); //processOutput = p.StandardOutput.ReadToEnd(); //if (!processOutput.Contains("ISP done.")) //processResultOk = false; } //if (processResultOk) { var p = new Process { StartInfo = { CreateNoWindow = false, UseShellExecute = false, FileName = "batchisp", Arguments = "-device at32uc3b0256 -hardware usb -operation start reset 0" } }; //p.StartInfo.CreateNoWindow = true; //p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); //processOutput = p.StandardOutput.ReadToEnd(); //if (!processOutput.Contains("Summary: Total 5 Passed 5 Failed 0")) //processResultOk = false; } Thread.Sleep(1000); if (onComplete != null) { _uiNotifier.Notify(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Ok, "Прошивка ПО завершена."))); } } catch (Exception ex) { if (onComplete != null) { _uiNotifier.Notify(() => onComplete(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, "Не удалось прошить ПО. Ошибка: " + ex))); } } }); }
public void GetStatisticAsync(Action <Exception, IEnumerable <string> > callback) { _bworker.AddWork(() => { try { //var beginTime = _psnDataInformation.BeginTime.HasValue ? _psnDataInformation.BeginTime.Value : (_psnDataInformation.SaveTime.HasValue ? _psnDataInformation.SaveTime.Value : DateTime.Now); var pagesIndex = _psnDataPaged.GetPagesIndex(); int totalPagesInLog = 0; int badPagesCount = 0; int notDatedPagesCount = 0; int normalPagesCount = 0; var timeBackPairs = new List <Tuple <IPsnPageIndexRecord, IPsnPageIndexRecord> >(); var numberSkipPairs = new List <Tuple <IPsnPageIndexRecord, IPsnPageIndexRecord> >(); IPsnPageIndexRecord prevRecord = null; foreach (var pageInfo in pagesIndex) { totalPagesInLog++; switch (pageInfo.PageInfo) { case PsnPageInfo.BadPage: badPagesCount++; break; case PsnPageInfo.NormalPage: normalPagesCount++; break; } if (!pageInfo.PageTime.HasValue) { notDatedPagesCount++; } if (prevRecord != null) { if (prevRecord.PageInfo == PsnPageInfo.NormalPage && pageInfo.PageInfo == PsnPageInfo.NormalPage) { if (pageInfo.PageNumber - prevRecord.PageNumber != 1 && !(pageInfo.PageNumber == 0 && prevRecord.PageNumber == 255)) { numberSkipPairs.Add(new Tuple <IPsnPageIndexRecord, IPsnPageIndexRecord>(prevRecord, pageInfo)); } if (prevRecord.PageTime.HasValue && pageInfo.PageTime.HasValue) { if (pageInfo.PageTime.Value < prevRecord.PageTime.Value) { timeBackPairs.Add(new Tuple <IPsnPageIndexRecord, IPsnPageIndexRecord>(prevRecord, pageInfo)); } } } } prevRecord = pageInfo; } var result = new List <string> { "Страниц в логе: " + totalPagesInLog, "Страниц, не распознанных как страницы данных ПСН, в логе: " + badPagesCount, "Страниц с данными ПСН: " + normalPagesCount, "Страниц без временной метки (из числа страниц с данными): " + notDatedPagesCount }; var lineTime = "Число обратных временных переходов в логе: " + timeBackPairs.Count + ": "; foreach (var pair in timeBackPairs) { lineTime += " 0x" + pair.Item1.AbsolutePositionInStream.ToString("X") + "-0x" + pair.Item2.AbsolutePositionInStream.ToString("X"); } result.Add(lineTime); var lineBack = "Число скачков номера страницы: " + numberSkipPairs.Count + ": "; foreach (var pair in numberSkipPairs) { lineBack += " 0x" + pair.Item1.AbsolutePositionInStream.ToString("X") + "-0x" + pair.Item2.AbsolutePositionInStream.ToString("X"); } result.Add(lineBack); var isPagesFlowErrorAccured = timeBackPairs.Count > 1 || (timeBackPairs.Count <= 1 && numberSkipPairs.Count != timeBackPairs.Count); if (isPagesFlowErrorAccured) { if (_logIntegrity != PsnLogIntegrity.PagesFlowError) { _logIntegrity = PsnLogIntegrity.PagesFlowError; _uiNotifier.Notify(() => IsSomethingWrongWithLogChanged.SafeInvoke(this, new System.EventArgs())); } } else { if (_logIntegrity != PsnLogIntegrity.Ok) { _logIntegrity = PsnLogIntegrity.Ok; _uiNotifier.Notify(() => IsSomethingWrongWithLogChanged.SafeInvoke(this, new System.EventArgs())); } } _uiNotifier.Notify(() => { callback?.Invoke(null, result); }); } catch (Exception ex) { _uiNotifier.Notify(() => { callback?.Invoke(ex, null); }); } }); }