public DeviceCalibrationVM(ICalibrator calibrator, IDeviceInitializationVM deviceInitialization, BusyObject busy) { Calibrator = calibrator; _deviceInitialization = deviceInitialization; _busy = busy; Begin = new ActionCommand(beginAsync, () => _busy.IsNotBusy && Calibrator.Model.Begin.IsCanExecute, _busy, Calibrator.Model.Begin); Discard = Calibrator.Model.Discard; async Task beginAsync() { var isExecuted = await _deviceInitialization.Initialize.ExecuteIfCanBeExecutedAsync(); if (!isExecuted) { Logger.LogErrorEverywhere("Не удалось произвести инициализацию"); } else { if (_deviceInitialization.IsInitialized) { await Calibrator.Model.Begin.ExecuteIfCanBeExecutedAsync(); } else { Logger.LogErrorEverywhere("Устройство не инициализировано, калибровка запрещена"); } } } }
public DeviceInitializationVM(IRUSDevice device, BusyObject busy, WriteFilesByDefaultVM writeFilesByDefault) { _busy = busy; _validator = new DeviceValidator(device); Initialize = new ActionCommand(initialize, _busy); WriteFilesByDefault = writeFilesByDefault; async Task initialize() { using (_busy.BusyMode) { try { IsInitialized = await _validator.CheckFilesAsync(); if (IsInitialized) { Logger.LogOKEverywhere("Устройство инициализировано"); } else { Logger.LogErrorEverywhere("Устройство не инициализировано"); } } catch (Exception ex) { Logger.LogErrorEverywhere("Ошибка инициализации устройства", ex); IsInitialized = false; } } } }
public DeviceStatusVM(IRUSDevice device, BusyObject isBusy) { _device = device ?? throw new ArgumentNullException(nameof(device)); _isBusy = isBusy ?? throw new ArgumentNullException(nameof(isBusy)); _device.TryGetFeature <StatusFeature>().StatusAcquired += DeviceStatusVM_StatusAcquired; Update = new ActionCommand(update, () => !_isBusy, _isBusy); async Task update() { using (_isBusy.BusyMode) { var statusReadResult = await _device.TryReadStatusAsync(DeviceOperationScope.DEFAULT, CancellationToken.None); if (statusReadResult.Status != ReadStatus.OK) { Info.Clear(); Flags.Clear(); } else { Logger.LogOKEverywhere("Статус обновлен"); } } } }
public RUSModuleSetDirectionVM(IRUSDevice device, BusyObject busy) { _device = device ?? throw new ArgumentNullException(nameof(device)); IsBusy = busy ?? throw new ArgumentNullException(nameof(busy)); var descriptors = Requests.GetRequestDescription(_device.Id, Command.KEEP_MTF); // All other commands have the same body Entities = new EnhancedObservableCollection <CommandEntityVM>( descriptors.UserCommandDescriptors.Select(d => new CommandEntityVM(d))); SendCommand = new ActionCommand <Command>(sendAsync, IsBusy); async Task sendAsync(CommandParameter <Command> command) { using (IsBusy.BusyMode) { assertViewValues(); if (command.IsSet) { await _device.BurnAsync(command.Value, Entities.Select(e => e.Entity), null, null); Logger.LogOKEverywhere($"Команда отправлена"); } else { Debugger.Break(); // Binding error } } } }
public WidgetsManager(SerialPortVM serialPortVM, IScopeProvider scopeProvider, BusyObject busy) { _scopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); _busy = busy ?? throw new ArgumentNullException(nameof(busy)); serialPortVM.ConnectionClosed += SerialPortVM_ConnectionClosed; serialPortVM.ConnectionEstablished += SerialPortVM_ConnectionEstablished; _scopeProvider.ScopeChanged += _scopeProvider_ScopeChanged; }
public DeviceDataRequestVM(IRUSDevice device, BusyObject isBusy, IDataProvider[] dataProviders) { _device = device; IsBusy = isBusy; DeviceDataVM = new DeviceDataVM(_device); GetDataRequest = new ActionCommand(getData, IsBusy) { CanBeExecuted = _device.SupportedCommands.Contains(Command.DATA) }; GetDataPacketConfigurationRequest = new ActionCommand(getDataPacketFormat, IsBusy) { CanBeExecuted = _device.SupportedCommands.Contains(Command.DATA_PACKET_CONFIGURATION_FILE) }; foreach (var dataProvider in dataProviders) { if (dataProvider is IDecoratedDataProvider drp) { drp.DecoratedDataRowAquired += updateData; } else { dataProvider.DataRowAquired += updateData; } } async Task getDataPacketFormat() { using (IsBusy.BusyMode) { var result = await _device.ReadAsync(Command.DATA_PACKET_CONFIGURATION_FILE, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status == ReadStatus.OK) { Logger.LogOKEverywhere($"Формат пакета данных обновлен"); } else { Logger.LogErrorEverywhere($"Ошибка обновления формата пакета данных"); } } } async Task getData() { using (IsBusy.BusyMode) { var data = await _device.ReadAsync(Command.DATA, DeviceOperationScope.DEFAULT, CancellationToken.None); if (data.Status == ReadStatus.OK) { updateData(data.Entities.GetViewEntities()); } } } }
static IEnumerable <ICalibrator> getCalibrators( IRUSDevice device, Func <FileType, IEnumerable <IDataEntity>, Task> saveCalibrationFileAsync, BusyObject isBusy) { return(CalibratorsFactory .GetCalibrators(device, isBusy, saveCalibrationFileAsync) .ToArray()); }
static IEnumerable <Command> getCommands(IRUSDevice device, BusyObject isBusy) { return(EnumUtils .GetValues <Command>() .Select(a => (Addr: a, Info: a.GetInfo())) .Where(i => i.Info != null && i.Info.IsCommand && i.Info.IsSupportedForDevice(device.Id)) .Select(i => i.Addr)); }
public DevicesVM(SerialPortVM serialPortVM, IRUSConnectionInterface connectionInterface, BusyObject isBusy) { IsBusy = isBusy; new DefaultFilesKeeper().CreateAllFiles(TEMPLATES_DIR_PATH, WidgetsLocator.Resolve <IFileExtensionFactory>()); SupportedDevices = DevicesFactory .InstantiateSupported(connectionInterface) .OrderBy(d => d.Id) .Select(d => new DeviceSlimVM(serialPortVM, d, IsBusy, d.Children.OrderBy(cd => cd.Id).Select(cd => new DeviceSlimVM(serialPortVM, cd, IsBusy)).ToArray())) .ToObservable(); PropertyChanged += _propertyHolder_PropertyChanged; }
public FlashDumpLoadVM(RUSDeviceId rusDevice, BusyObject isBusy) { IsBusy = isBusy; DataStorageVM = new FlashDataStorageVM(this); Load = new ActionCommand(loadAsync, IsBusy); Cancel = new ActionCommand(cancelAsync, () => _currentOperation != null, IsBusy); async Task loadAsync() { using (IsBusy.BusyMode) { var path = IOUtils.RequestFileOpenPath("BIN (*.bin)|*.bin"); if (path == null) { return; } try { _currentOperation = new AsyncOperationInfo().UseInternalCancellationSource(); _currentOperationTask = LoadAsync(path, _currentOperation); Cancel.Update(); await _currentOperationTask; Logger.LogOKEverywhere("Дамп Flash успешно загружен"); } catch (OperationCanceledException) { Logger.LogInfoEverywhere("Чтение дампа Flash отменено"); PointsSource = null; } catch (Exception ex) { Logger.LogError("Ошибка загрузки дампа", $"-MSG", ex); PointsSource = null; } finally { _currentOperationTask = null; _currentOperation = null; } } } async Task cancelAsync() { _currentOperation?.Cancel(); } }
public GyroTemperatureCalibrationVM( BusyObject busy, IRUSDevice device, Func <FileType, IEnumerable <IDataEntity>, Task> saveCalibrationFileAsync) : base(busy, device, saveCalibrationFileAsync) { AveragePoints = new DoubleValueVM(new Interval(10, 1000), true, 0, () => _calibrator.AveragePoints, v => _calibrator.AveragePoints = v.Round(), _calibrator); AveragePoints.ModelValue = 20; RotationSpeed = new RotationSpeedVM(_calibrator); }
async void Db_SavingChanges(BusyObject savingChanges) { using (savingChanges.BusyMode) { S.Db.ChangeTracker.DetectChanges(); foreach (var entry in S.Db.ChangeTracker.Entries().ToArray()) { if (!entry.State.IsOneOf(EntityState.Unchanged, EntityState.Detached)) { var entity = entry.Entity; if (entity is ProfileStatus) // Update blog statistic { var stateProperty = entry.Property(nameof(ProfileStatus.State)); if (entry.State == EntityState.Added) { await updateUsersWithStateCount(stateProperty.OriginalValue.To <ProfileState>(), stateProperty.CurrentValue.To <ProfileState>()); } else if (stateProperty.IsModified) { await updateUsersWithStateCount(stateProperty.OriginalValue.To <ProfileState>(), stateProperty.CurrentValue.To <ProfileState>()); } } if (entity is Post post) // Update blog statistic { _queue += () => updatePostsCount(post, entry.State == EntityState.Added); } if (entity is Commentary commentary) // Update blog statistic { _queue += () => updateCommentariesCount(commentary, entry.State == EntityState.Added); } else if (entry.Entity is IViewStatistic viewStatistic && entry.State == EntityState.Modified) // Update blog statistic { var totalViewsProperty = entry.Property(nameof(IViewStatistic.TotalViews)); var registredUserViewsProperty = entry.Property(nameof(IViewStatistic.RegisteredUserViews)); var totalViewsDelta = totalViewsProperty.CurrentValue.To <int>() - totalViewsProperty.OriginalValue.To <int>(); var registredUserViewsDelta = registredUserViewsProperty.CurrentValue.To <int>() - registredUserViewsProperty.OriginalValue.To <int>(); if (viewStatistic is IViewStatistic <Commentary> commentaryVStat) { await updateCommentariesViewStatisticAsync(commentaryVStat.Owner.Id, totalViewsDelta, registredUserViewsDelta); } else if (viewStatistic is IViewStatistic <Post> postVStat) { await updatePostsViewStatisticAsync(postVStat.Owner.Id, totalViewsDelta, registredUserViewsDelta); } } else if (entity is UserAction userAction && entry.State == EntityState.Added) // Update user stat { updateUserActionsStatistic(userAction); }
public WriteFilesByDefaultVM(IRUSDevice device, BusyObject isBusy) { IsBusy = isBusy; WriteAllFilesByDefault = new ActionCommand(writeDefaultFiles, isBusy); SerialNumber.ModelValue = 1; Modification.ModelValue = "??"; async Task writeDefaultFiles() { using (isBusy.BusyMode) { SerialNumber.AssertValue(); Modification.AssertValue(); if (!UserInteracting.RequestAcknowledgement("Запись файлов по умолчанию", "Данная операция перезапишет все файлы файлами по умолчанию-NL-NLПродолжить?")) { return; } var hadError = false; var date = DateTime.UtcNow; foreach (var file in Files.Descriptors.Where(d => d.Key.TargetDeviceId == device.Id)) { var entities = file.Value.Descriptors.Select(d => d.FileDefaultDataEntity); entities = Files.SetBurnDate(entities, date); entities = Files.SetSerialNumber(entities, SerialNumber.ModelValue.ToInt32()); entities = Files.SetFileEntity(entities, FileEntityType.MODIFICATION, Modification.ModelValue); var request = file.Key.FileType.GetRequestAddress(); var result = await device.BurnAsync(request, entities, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status != BurnStatus.OK) { Logger.LogErrorEverywhere("Ошибка операции"); hadError = true; break; } } if (!hadError) { SuccessfullyWritten?.Invoke(this); } } } }
public MainVM() { var locker = new SemaphoreSlim(1, 1); var port = new InterfaceAggregator( new COMPortAdapter(new SerialPort(), COM_TIMEOUT, COM_TIMEOUT, locker), new TestCOMInterface(locker), new FTDIInterface(FTDI_TIMEOUT, FTDI_TIMEOUT, locker), new TestFTDIInterface(locker)); var busy = new BusyObject(); COMPortVM = new SerialPortVM(port, busy); DevicesVM = new DevicesVM(COMPortVM, new SerialPortRUSConnectionInterface(port), busy); LogVM = new LogVM(); new WidgetsManager(COMPortVM, DevicesVM, busy); }
public ShockSensorCalibrationVM( BusyObject busy, IRUSDevice device, Func <FileType, IEnumerable <IDataEntity>, Task> saveCalibrationFileAsync) : base(busy, device, saveCalibrationFileAsync) { PulseDurationVM = new PulseDurationVM(IsBusy, _calibrator); SetDefaultThresholds = new ActionCommand( (Action)Calibrator.ResetThresholdsToDefault, IsBusy ); CalculateThresholds = new ActionCommand( (Action)Calibrator.RecalculateThresholds, () => Calibrator.IsTestingFinished && !IsBusy, IsBusy, Calibrator ); }
public CalibrationBaseVM( BusyObject busy, IRUSDevice device, Func <FileType, IEnumerable <IDataEntity>, Task> saveCalibrationFileAsync) { _device = device; _calibrator = instantiateCalibrator(); DataProvider = _calibrator is IDataProvider ? (IDataProvider)_calibrator : (IDataProvider)(_device = new RUSDeviceDataProviderProxy(_device)); _calibrator.RedirectAnyChangesTo(this, () => PropertyChanged, nameof(HasCalibrationBegun)); IsBusy = busy; _fileGenerator = new CalibrationFileGenerator(device, calibrationFileType, "01"); _saveCalibrationFileAsync = saveCalibrationFileAsync; _calibrator.PropertyChanged += (o, e) => updateModelBindings(); updateModelBindings(); StartMeasure = new ActionCommand <TMode>(startMeasureAsync, m => canStartMeasure(m) && !IsBusy, IsBusy, this, _calibrator); CancelMeasure = new ActionCommand(cancelMeasureAsync); FinishMeasure = new ActionCommand <TMode>(finishMeasureAsync, m => canFinishMeasure(m) && _calibrator.State == MeasureState.WAITING_FOR_FINISH && (!m.IsSet || Equals(getModelsTestMode(m.Value), _calibrator.CurrentMode)), _calibrator); ExportMeasureResults = new ActionCommand(exportMeasureResultAsync, () => !IsBusy && canExport, this, _calibrator, IsBusy); ImportMeasureResults = new ActionCommand(importMeasureResultAsync, IsBusy); SaveCalibrationFile = new ActionCommand(saveCalibrationsAsync, () => !IsBusy && _calibrator.CallibrationCanBeGenerated, IsBusy, _calibrator); CancelMeasure.CanBeExecuted = false; Begin = new ActionCommand(beginAsync, () => !HasCalibrationBegun && !IsBusy, IsBusy, _calibrator); Discard = new ActionCommand(discardAsync, () => HasCalibrationBegun && !IsBusy, IsBusy, _calibrator); }
/// <summary> /// /// </summary> /// <param name="device"></param> /// <param name="commandAddress"></param> /// <param name="handlerWidget">optional</param> /// <param name="isBusy"></param> public DeviceCommandVM(IRUSDevice device, Command commandAddress, ICommandHandlerWidget handlerWidget, BusyObject isBusy) { _device = device; _request = commandAddress; IsBusy = isBusy; Widget = handlerWidget; var requestinfo = Requests.GetRequestDescription(_device.Id, _request); Entities.AddRange(requestinfo.UserCommandDescriptors .Select(d => new CommandEntityVM(d)) .ToArray()); Name = _request.GetInfo().CommandName; Send = new ActionCommand(burnAsync, IsBusy); Read = new ActionCommand(readAsync, IsBusy); Cancel = new ActionCommand(cancelAsync, () => _currentRequest != null, IsBusy); Read.CanBeExecuted = IsReadSupported = commandAddress.GetInfo().IsReadSupported; Send.CanBeExecuted = IsSendSupported = commandAddress.GetInfo().IsWriteSupported; Cancel.CanBeExecuted = Widget?.Settings?.AllowCancelling ?? false; Progress = (Widget?.Settings?.ShowProgress ?? false) ? new RichProgress() : null; async Task burnAsync() { using (IsBusy.BusyMode) { Logger.LogInfoEverywhere($"Отправка комманды записи \"{Name}\""); if (Widget != null) { throw new NotImplementedException(); } assertViewValues(); var entitiesToWrite = Entities.Select(e => e.Entity).ToArray(); var allEntitiesToWrite = requestinfo.BuildWriteRequestBody(entitiesToWrite); var result = await _device.BurnAsync(_request, allEntitiesToWrite, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status == BurnStatus.OK) { if (IsReadSupported) { await verifyBurnAsync(allEntitiesToWrite); } else { Logger.LogOKEverywhere("Запись завершена"); } } else { Logger.LogErrorEverywhere("Ошибка отправки команды"); } } async Task verifyBurnAsync(IEnumerable <IDataEntity> allEntitiesToWrite) { var readEntities = await readAsync(); if (readEntities != null) { var isVerified = readEntities .Select(e => e.Value) .SequenceEqual(allEntitiesToWrite.Select(e => e.Value)); if (isVerified) { Logger.LogOKEverywhere("Запись завершена"); } else { Logger.LogWarningEverywhere("Записанные данные не совпадают с прочитанными"); } } } } async Task <IEnumerable <IDataEntity> > readAsync() { using (IsBusy.BusyMode) { Logger.LogInfoEverywhere($"Отправка комманды чтения \"{Name}\""); if (Widget != null) { await widgetsHandlerAsync(); return(null); } else { var result = await _device.ReadAsync(_request, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status == ReadStatus.OK) { foreach (var entity in Entities) { var match = result.Entities.First(e => e.Descriptor.Equals(entity.Descriptor)); entity.EntityValue.ModelValue = match.Value; } assertViewValues(); Logger.LogOKEverywhere("Чтение завершено"); return(result.Entities); } else { Logger.LogErrorEverywhere("Ошибка отправки команды"); return(null); } } } async Task widgetsHandlerAsync() { try { Progress.Reset(); _currentRequest = new AsyncOperationInfo(Progress).UseInternalCancellationSource(); Cancel.Update(); await Widget.Model.OnReadAsync(_currentRequest); } catch (OperationCanceledException) { Logger.LogInfoEverywhere("Команда была отменена"); } catch (Exception ex) { Logger.LogErrorEverywhere("Ошибка отправки команды", ex); } finally { _currentRequest = null; Cancel.Update(); } } } async Task cancelAsync() { _currentRequest.Cancel(); } void assertViewValues() { foreach (var e in Entities) { e.EntityValue.AssertValue(); } } }
public PulseDurationVM(BusyObject isBusy, ShockSensorCalibrator calibrator) { _isBusy = isBusy; _calibrator = calibrator; _previousCheckedOption = ImpulseDurations.Single(o => o.IsChecked); }
public RUSTelemetryStreamSenderVM(IRUSDevice device, BusyObject isBusy) { _isBusy = isBusy ?? throw new ArgumentNullException(nameof(isBusy)); _device = device ?? throw new ArgumentNullException(nameof(device)); ChooseFile = new ActionCommand(chooseFileAsync, _isBusy); Start = new ActionCommand(async() => { _sendingOperation = startSendingAsync(); Stop.Update(); await _sendingOperation; }, () => _currentData != null && _isBusy.IsNotBusy, _isBusy); Stop = new ActionCommand(stopSending, () => _sendingOperation != null, _isBusy); async Task stopSending() { _operationInfo.Cancel(); await _sendingOperation; } async Task startSendingAsync() { using (_isBusy.BusyMode) { try { Logger.LogOKEverywhere("Передача начата"); _operationInfo = new AsyncOperationInfo(Progress).UseInternalCancellationSource(); _operationInfo.Progress.Optimize = false; _operationInfo.Progress.MaxProgress = _currentData.Count; var sw = Stopwatch.StartNew(); var sendedCurveTotalDuration = TimeSpan.Zero; for (int i = 0, frameI = 0; i < _currentData.Count; frameI++) { TimeSpan duration = TimeSpan.Zero; var frame = new List <RegData>(); await Task.Run(async() => { var first = await _currentData[i]; frame.Add(first); for (; i < _currentData.Count - 1; i++) { var item = await _currentData[i + 1]; if (item.Time <= frame.LastElement().Time) { continue; } else { frame.Add(item); duration = item.Time - first.Time; if (duration.TotalMilliseconds >= FRAME_DURATION) { i++; break; } } } i++; }); if (i == _currentData.Count) { unchecked { frameI = (int)uint.MaxValue; }; Logger.LogOKEverywhere("Отправка файла завершена"); } var durationMs = duration.TotalMilliseconds.Round(); var frameData = frame.Select(d => d.Row[0]).ToArray(); var request = Requests.BuildRegDataFramePacket(frameI, durationMs, frameData); var result = await _device.BurnAsync(Command.REG_DATA_FRAME, request, DeviceOperationScope.DEFAULT, CancellationToken.None); //if (result.Status == BurnRequestStatus.OK) if (true) { var response = result.Response == null ? new ulong[0] : result.Response.Skip(6).SkipFromEnd(2).GroupBy(8).Select(bs => Deserialize(bs)).ToArray(); foreach (var pointI in frameData.Length.Range()) { var entities = new List <ViewDataEntity>(); entities.Add(new ViewDataEntity("Pressure", frameData[pointI], true)); if (response.Length > pointI) { entities.Add(new ViewDataEntity($"Response", response[pointI], true)); } else { entities.Add(new ViewDataEntity($"Response", "")); } var decoration = (Progress.Progress.Round() + pointI) % _avgSampleRate == 0 ? RowDecoration.LINE : RowDecoration.NONE; DecoratedDataRowAquired?.Invoke(entities, decoration); } ulong Deserialize(IEnumerable <byte> data) { return(BitConverter.ToUInt64(data.Take(8).Reverse().ToArray(), 0)); } sendedCurveTotalDuration += duration; _operationInfo.Progress.Report(i + 1); await Task.Delay( (sendedCurveTotalDuration.TotalMilliseconds - sw.Elapsed.TotalMilliseconds - PREEMPTIVE_READ_DURATION).Round().NegativeToZero(), _operationInfo.CancellationToken); } else { Logger.LogErrorEverywhere("Ошибка передачи кадра"); frameI--; i -= frame.Count; } _operationInfo.CancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { Logger.LogInfoEverywhere("Пересылка отменена"); } catch (Exception ex) { Logger.LogErrorEverywhere("Цикл отправки завершился с ошибкой", ex); } finally { _sendingOperation = null; _operationInfo = null; Progress.Reset(); Stop.Update(); } } } async Task chooseFileAsync() { using (_isBusy.BusyMode) { try { var path = IOUtils.RequestFileOpenPath("RAW (*raw)|*.raw"); if (path == null) { Logger.LogInfoEverywhere("Файл не выбран"); return; } var file = new FileStream(path, FileMode.Open); _currentData?.Dispose(); _currentData = new RegDataReader(file); ChooseFile.Update(); using (Parameters.EventSuppressingMode) { Parameters.Clear(); var first = await _currentData[0]; var last = await _currentData[_currentData.Count - 1]; var duration = last.Time - first.Time; _avgSampleRate = (_currentData.Count / duration.TotalSeconds).Round(); Parameters.Add(new KeyValuePair <string, string>("Длительность (часов)", duration.TotalHours.Round().ToString())); Parameters.Add(new KeyValuePair <string, string>("Частота семплирования", (_currentData.Count / duration.TotalSeconds).ToStringInvariant("F2"))); } } catch (Exception ex) { Logger.LogErrorEverywhere("Ошибка при загрузке", ex); _currentData?.Dispose(); } } } }
public ActionCommand( Func <Task> actionAsync, BusyObject busy) : base(actionAsync, () => !busy, busy) { }
public ActionCommand(Action action, BusyObject busy) : this(action, () => !busy.IsBusy, busy) { }
public static IWidget[] ResolveWidgetsForScope(IRUSDevice scopeDevice, BusyObject busy) { if (_models.ContainsKey(scopeDevice)) { throw new InvalidOperationException("Only one set of widgets per scope is allowed"); } using (var core = new DICore()) { registerBasicServices(); instantiateWidgets(); var widgets = core.Container.ResolveAll <IWidget>().ToArray(); _allWidgets.AddRange(widgets.Select(w => new WidgetInfo(w, scopeDevice))); _models[scopeDevice] = core.Container.TryResolveAll <IDeviceHandler>()?.ToList() ?? new List <IDeviceHandler>(); return(widgets); void registerBasicServices() { core.Container.Register(scopeDevice); core.Container.Register(scopeDevice.Name); // We're registering string. Dont be confused core.Container.Register(busy); } void instantiateWidgets() { var instantiator = core.InstantiationStrategy; var instantiationCoroutines = widgetsFactory(core.Container).ToArray(); instantiator.ExecuteCoroutines(instantiationCoroutines); } } ////////////////////////////////////// IEnumerable <IEnumerator <ResolutionStepResult> > widgetsFactory(IDIContainer container) { string dataViewScope = nameof(dataViewScope); string flashDumpViewScope = nameof(flashDumpViewScope); yield return(injectExporters(container, dataViewScope)); yield return(DeviceInitialization.InstantiationCoroutine(dataViewScope, container)); yield return(DeviceFiles.InstantiationCoroutine(dataViewScope, container)); yield return(DeviceStatus.InstantiationCoroutine(dataViewScope, container)); yield return(DataRequest.InstantiationCoroutine(dataViewScope, container)); yield return(DataView.InstantiationCoroutine("Данные", dataViewScope, container)); foreach (var command in getCommands(scopeDevice, busy)) { if (command == Command.DOWNLOAD_FLASH && Command.DOWNLOAD_FLASH.GetInfo().IsSupportedForDevice(scopeDevice.Id)) { yield return(FlashUploadCommand.InstantiationCoroutine(flashDumpViewScope, container)); } yield return(DeviceCommand.InstantiationCoroutine(command, dataViewScope, container)); } foreach (var calibrator in getCalibrators(scopeDevice, new FileSaver(scopeDevice.Id, FileExtensionFactory.Instance).SaveCalibrationFileAsync, busy).ToArray()) { yield return(DeviceCalibration.InstantiationCoroutine(calibrator, dataViewScope, container)); yield return(injectCalibrationWidgets(container, calibrator)); } foreach (var widget in deviceSpecificWidgetsFactory()) { yield return(widget); } yield return(DataViewSettings.InstantiationCoroutine(false, dataViewScope, container)); IEnumerable <IEnumerator <ResolutionStepResult> > deviceSpecificWidgetsFactory() { if (scopeDevice.Id.IsOneOf(RUSDeviceId.RUS_TECHNOLOGICAL_MODULE, RUSDeviceId.RUS_MODULE, RUSDeviceId.EMC_MODULE)) { yield return(FlashDumpLoad.InstantiationCoroutine(flashDumpViewScope, container)); yield return(DataView.InstantiationCoroutine("Данные дампа Flash", flashDumpViewScope, container)); yield return(DataViewSettings.InstantiationCoroutine(true, flashDumpViewScope, container)); yield return(injectExporters(container, flashDumpViewScope)); } if (scopeDevice.Id.IsOneOf(RUSDeviceId.RUS_MODULE)) { yield return(RUSModuleSetDirection.InstantiationCoroutine(dataViewScope, container)); yield return(RUSTelemetryStreamSender.InstantiationCoroutine(dataViewScope, container)); } } } }
public static IEnumerable <ICalibrator> GetCalibrators( IRUSDevice device, BusyObject uiBusy, Func <FileType, IEnumerable <IDataEntity>, Task> saveCalibrationFileAsync) { var scope = device.Id.GetEnumValueDescription(); switch (device.Id) { case RUSDeviceId.INCLINOMETR: { var vm = new TemperatureCalibrationVM(uiBusy, device, saveCalibrationFileAsync); var view = new InclinometrTemperatureCalibration() { FunctionId = new WidgetIdentity(vm.CalibrationName, scope, null), ViewModel = vm }; var errorWidget = new InclinometrTemperatureCalibrationErrors() { FunctionId = new WidgetIdentity("Температурные отклонения", scope, null), ViewModel = new TemperatureCalibrationErrorsVM(vm.Calibrator) }; yield return(new Calibrator(vm, view, errorWidget)); } { var vm = new AngularCalibrationVM(uiBusy, device, saveCalibrationFileAsync); var view = new InclinometrAngularCalibration() { FunctionId = new WidgetIdentity(vm.CalibrationName, scope, null), ViewModel = vm }; var errorWidget = new InclinometrAngularCalibrationErrors() { FunctionId = new WidgetIdentity("Угловые отклонения", scope, null), ViewModel = new AngularCalibrationErrorsVM(vm.Calibrator) }; yield return(new Calibrator(vm, view, errorWidget)); } break; case RUSDeviceId.SHOCK_SENSOR: { var vm = new ShockSensorCalibrationVM(uiBusy, device, saveCalibrationFileAsync); var view = new ShockSensorCalibration() { FunctionId = new WidgetIdentity(vm.CalibrationName, scope, null), ViewModel = vm }; yield return(new Calibrator(vm, view)); } break; case RUSDeviceId.ROTATIONS_SENSOR: { var vm = new GyroTemperatureCalibrationVM(uiBusy, device, saveCalibrationFileAsync); var view = new GyroTemperatureCalibration() { FunctionId = new WidgetIdentity(vm.CalibrationName, scope, null), ViewModel = vm }; yield return(new Calibrator(vm, view)); } break; } }
public FlashUploadCommandVM(IRUSDevice device, IFlashDumpDataParserFactory parserFactory, IFlashDumpSaver flashDumpSaver, IFlashDumpLoader dumpLoader, BusyObject busy) { _device = device ?? throw new ArgumentNullException(nameof(device)); _parserFactory = parserFactory; _flashDumpSaver = flashDumpSaver; IsBusy = busy ?? throw new ArgumentNullException(nameof(busy)); SaveDump = new ActionCommand(saveDumpAsync, () => _dump != null && IsBusy.IsNotBusy, IsBusy); async Task saveDumpAsync() { try { var path = IOUtils.RequestFileSavingPath("BIN(*.bin)|*.bin"); if (path != null) { using (var targetDumpFile = File.Create(path)) { await _dump.SaveDumpAsync(targetDumpFile, _flashDumpSaver, new AsyncOperationInfo()); } await dumpLoader.LoadAsync(path, new AsyncOperationInfo()); UserInteracting.ReportSuccess("Сохранение дампа Flash-памяти", "Файл успешно сохранен"); } } catch (Exception ex) { Logger.LogErrorEverywhere("Ошибка сохранения дампа Flash-памяти", ex); } } }