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()); } } } }
public async Task <bool> CheckFilesAsync() { Logger.LogInfoEverywhere("Начата проверка файлов"); using (Logger.Indent) { var serials = new List <object>(); foreach (var fileRequest in _device.SupportedCommands.Where(r => r.IsFileRequest())) { var fileType = fileRequest.GetFileType(); var result = await _device.ReadAsync(fileRequest, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status == ReadStatus.OK) { var actualSerial = Files.GetFileEntity(result.Entities, FileEntityType.SERIAL_NUMBER).Value; if (Equals(actualSerial, Files.DEFAULT_SERIAL)) { Logger.LogWarningEverywhere($"Файл \"{fileType.GetInfo().FileName}\" не установлен"); return(false); } serials.Add(actualSerial); if (serials.Any(s => !Equals(s, actualSerial))) { Logger.LogWarningEverywhere($"Серийные номера файлов не совпадают"); return(false); } } else { Logger.LogErrorEverywhere($"Не удалось прочитать файл \"{fileType.GetInfo().FileName}\""); return(false); } } return(true); } }
public async Task <IEnumerable <IDataEntity> > GenerateAsync(IEnumerable <CalibrationFileEntity> coefficients) { var result = await _device.ReadAsync(_calibrationFileType.GetInfo().RequestAddress, DeviceOperationScope.DEFAULT, CancellationToken.None); if (result.Status != ReadStatus.OK) { throw new InvalidOperationException("Не удалось запросить файл калибровки для определения серийного номера и модификации прибора."); } var serialNumber = Files.GetFileEntity(result.Entities, FileEntityType.SERIAL_NUMBER); var modification = Files.GetFileEntity(result.Entities, FileEntityType.MODIFICATION); return(generateFile()); IEnumerable <IDataEntity> generateFile() { var fileInfo = new FileDescriptorsTarget(_calibrationFileType, _fileVersion, _device.Id); foreach (var descriptor in Files.Descriptors[fileInfo].Descriptors) { var entity = descriptor.FileDefaultDataEntity; if (descriptor.ValueFormat == DataEntityFormat.CALIBRATION_PACKET_ENTITIES_ARRAY) { entity = descriptor.InstantiateEntity(descriptor.Serialize(coefficients)); } if (entity.Descriptor.Name == serialNumber.Descriptor.Name) { yield return(serialNumber); } else if (entity.Descriptor.Name == modification.Descriptor.Name) { yield return(modification); } else { yield return(entity); } } } }
public async Task OnReadAsync(AsyncOperationInfo operationInfo) { if (_dump != null && !await UserInteracting.RequestAcknowledgementAsync("Начать загрузку дампа Flash-памяти", "Предыдущий дамп будет стерт из памяти программы-NL-NLПродолжить?")) { return; } operationInfo.Progress.Report(0); var formats = new Dictionary <RUSDeviceId, IEnumerable <IDataEntity> >(); switch (formatSource) { case FormatSource.MODULE: { var format = await _device.ReadAsync(Command.DATA_PACKET_CONFIGURATION_FILE, DeviceOperationScope.DEFAULT, operationInfo); if (format.Status != ReadStatus.OK) { Logger.LogErrorEverywhere("Не удалось получить формат данных"); return; } formats.Add(_device.Id, format.Entities); } break; case FormatSource.DEVICES: { foreach (var device in _device.Children.Concat(_device)) { var format = await device.ReadAsync(Command.FLASH_DATA_PACKET_CONFIGURATION, DeviceOperationScope.DEFAULT, operationInfo); if (format.Status == ReadStatus.OK) { formats.Add(device.Id, format.Entities); } else { Logger.LogWarningEverywhere($"Не удалось получить формат данных для устройства: {device.Id}"); } } } break; default: throw new NotSupportedException(); } if (formats.Count == 0) { Logger.LogErrorEverywhere($"Ни один из требуемых форматов не был получен"); return; } var reader = await FlashStreamReader.CreateAsync(_device.Id, formats, _parserFactory, operationInfo); var result = await _device.ReadAsync(Command.DOWNLOAD_FLASH, reader.FlashReadOperationScope, operationInfo); if (result.Status == ReadStatus.OK) { await reader.FinishAsync(operationInfo); _dump = reader; } }
public virtual Task <ReadRequestResult> ReadAsync(RequestAddress request, AsyncOperationInfo operationInfo = null) => _base.ReadAsync(request, operationInfo);
public virtual Task <ReadResult> ReadAsync(Command request, DeviceOperationScope scope, AsyncOperationInfo cancellation) { return(_base.ReadAsync(request, scope, cancellation)); }
/// <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(); } } }