public void SelectPortAsync(ISerialPortContainer portContainer, Action <Exception> comPortOpenedCallbackAction) { //_logger.Log("Закрытие ранее открытого порта (если был открыт) и открытие нового: " + portContainer, null); _backgroundWorker.AddWork(() => { Exception exception; try { if (_portContainer != null && _portContainer.IsOpen) { ClosePortSyncUnsafe(); } _portContainer = portContainer; _portContainer.Open(); _sendAbility = portContainer; _portContainerWithProgress = _portContainer as ISerialPortContainerWithProgress; exception = null; } catch (Exception ex) { exception = ex; } if (comPortOpenedCallbackAction != null) { _notifyWorker.AddWork(() => comPortOpenedCallbackAction(exception)); } }); }
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, "Внимание, репозиторий уже открыт"))); } }
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))); } } }); }
public void SendData(ushort netAddress, byte commandCode, byte[] data) { _sendDataWorker.AddWork(() => { var buffer = data.GetNetBuffer(netAddress, commandCode); Log.Log("buffer to send to UDP: " + buffer.ToText()); _client.Send(buffer, buffer.Length, _serverEndPoint); // no timeout, no chance to know whether data were transmitted }); }
void ReceivedCallback(IAsyncResult ar) { var socketWithBuffer = (SocketWithBuffer)ar.AsyncState; try { int bytesToRead = socketWithBuffer.S.EndReceive(ar); // сообщаем, что операция подсоединения завершена var data = new byte[bytesToRead]; Array.Copy(socketWithBuffer.B, data, bytesToRead); try { socketWithBuffer.S.BeginReceive(socketWithBuffer.B, 0, socketWithBuffer.B.Length, SocketFlags.None, ReceivedCallback, socketWithBuffer); } catch (Exception ex) { throw new Exception("Не удалось инициировать новый прием данных", ex); } // обработка данных в отдельном потоке: _notifyThreadWorker.AddWork(() => { try { if (bytesToRead >= 8) { if (DataReceived != null) { var netAddr = (ushort)(data[4] + (data[3] << 8)); var cmdCode = data[2]; var rcvData = new byte[bytesToRead - 8]; for (int i = 0; i < rcvData.Length; ++i) { rcvData[i] = data[i + 5]; } Logg("Данные в формате Интелекон успешно получены, netAddr=" + netAddr + " cmdCode=" + cmdCode + " info=" + rcvData.ToText() + ", оповещаем подписчиков"); DataReceived.SafeInvoke(this, new DataReceivedEventArgs(netAddr, cmdCode, rcvData)); // Вызывается не в основном потоке! } } } catch (Exception ex) { Logg("Ошибка при обработке данных, исключение: " + ex); } }); } catch (Exception ex) { Logg("Ошибка при завершении приема данных или при начале нового приема: " + ex); Disconnect(socketWithBuffer.S, ex); EstablishNewConnection(); } }
public QueuedScadaClient(IPAddress serverIpAddress, int serverPort, int localPort) { _serverEndPoint = new IPEndPoint(serverIpAddress, serverPort); _client = new UdpClient(new IPEndPoint(IPAddress.Any, localPort)); _receiveWorker = new SingleThreadedRelayQueueWorkerProceedAllItemsBeforeStopNoLog <Action>("ScadaUdpClientReceiveWorker", a => a(), ThreadPriority.BelowNormal, true, null); _receiveWorker.AddWork(DoReceiveInBackThread); _proceedReceivedDataWorker = new SingleThreadedRelayQueueWorkerProceedAllItemsBeforeStopNoLog <Action>("ScadaUdpClientProceedReceivedDataWorker", a => a(), ThreadPriority.Normal, true, null); _sendDataWorker = new SingleThreadedRelayQueueWorkerProceedAllItemsBeforeStopNoLog <Action>("ScadaUdpClientSendDataWorker", a => a(), ThreadPriority.Normal, true, null); }
public void BeginTest(Action testHasBegun, Action <double, TestSysStepResult, string> progressChanged, Action <TestSysResult> testComplete) { _sharedTestsWorker.AddWork(() => { testHasBegun.Invoke(); BeginTime = DateTime.Now; ProgressChanged = progressChanged; TestComplete = testComplete; IsTestRunning = true; _parameterSetter.SetParameterAsync(48, 1, exc => { }); ProgressChanged.Invoke(100, TestSysStepResult.Good, "48 параметр КСМ установлен в режим Охлаждение 100%"); }); }
public void SendDataAsync(string name, IInteleconCommand cmd, Action <ISendResultWithAddress> callback, IoPriority priority) { _sendQueueWorker.AddWork(() => { try { var bumizObj = GetBumizObject(name); var bumizChannel = GetBumizChannel(bumizObj.ChannelName); bumizChannel.SendInteleconCommandAsync(cmd, bumizObj.Address, bumizObj.Timeout, result => _notifyQueueWorker.AddWork(() => callback(result)), priority); } catch (Exception ex) { Log.Log("Во время отправки команды возникло исключение: " + ex); _notifyQueueWorker.AddWork(() => callback(new SendingResultWithAddress(null, ex, null, 0))); } }); }
/// <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)); } } }); }
private void ScheduleReadDataInBackground() { _readDataScheduler.AddWork(() => { while (true) { var waiter = new AutoResetEvent(false); _backgroundWorker.AddWork(() => { try { //_logger.Log("Reading bytes from port (8 bytes, timeout 1 second)..."); var bytes = _portContainer.Read(8, TimeSpan.FromSeconds(1)); //_logger.Log("Readed bytes from port: " + bytes.ToText()); _incomingBuffer.AddRange(bytes); //_logger.Log("INCOMING BUFFER BYTES COUNT AFTER READ = " + _incomingBuffer.Count); AnalyzeIncomingBuffer(); // analyzing in io thread to have possibility to reply } catch /*(Exception ex)*/ { //_logger.Log(ex); return; } finally { waiter.Set(); } }); // back to read data scheduler thread: waiter.WaitOne(); lock (_dontStopSync) { if (!_dontStop) { return; } } } }); }
public static void AddToQueueAndWaitExecution(this IWorker <Action> asyncWorker, Action a) { var signal = new ManualResetEvent(false); Exception exception = null; asyncWorker.AddWork(() => { try { a(); } catch (Exception ex) { exception = ex; } finally { signal.Set(); } }); signal.WaitOne(); if (exception != null) { throw exception; } }
private void DoReceiveInBackThread() { // TODO: stop receive cycle while (true) { try { IPEndPoint remotePoint = null; var receivedData = _client.Receive(ref remotePoint); // receive thread waits here _proceedReceivedDataWorker.AddWork(() => { // PROCEED DATA THREAD: Log.Log("Something received from: " + remotePoint + " data: " + receivedData.ToText()); if (Equals(remotePoint, _serverEndPoint)) { Log.Log("Remote point is correct"); if (receivedData.Length >= 8) { var netAddr = (ushort)(receivedData[4] + (receivedData[3] << 8)); var cmdCode = receivedData[2]; var rcvData = new byte[receivedData.Length - 8]; for (int i = 0; i < rcvData.Length; ++i) { rcvData[i] = receivedData[i + 5]; } Log.Log("Invoked data received event"); DataReceived?.Invoke(this, new DataReceivedEventArgs(netAddr, cmdCode, rcvData)); } } }); } catch (Exception e) { Console.WriteLine(e); //throw; } } }
public static void AddToQueueAndWaitExecution(this IWorker <Action> asyncWorker, Action a, TimeSpan timeout) { var sync = new object(); var signal = new ManualResetEvent(false); bool wasExecuted = false; Exception exception = null; asyncWorker.AddWork(() => { try { a(); lock (sync) { wasExecuted = true; } } catch (Exception ex) { exception = ex; } finally { signal.Set(); } }); signal.WaitOne(timeout); bool hasBeenExecuted; lock (sync) { hasBeenExecuted = wasExecuted; } if (!hasBeenExecuted) { throw new Exception("Таймаут операции"); } if (exception != null) { throw exception; } }
public void ReadSettingsAsync(bool forceRead, Action <Exception, IEngineSettings> callback) { // чтение настроек производится только для первого АИН if (forceRead == false) { var settings = _settingsStorageSettable.EngineSettings; if (settings != null) { _notifyWorker.AddWork(() => callback.Invoke(null, settings)); return; } } var sender = _commandSenderHost.Sender; if (sender == null) { throw new NullReferenceException("Порт передачи данных не открыт"); } var readSettingsCmd = new ReadEngineSettingsCommand(); _notifyWorker.AddWork(FireEventEngineSettingsReadStarted); _logger.Log("Чтение настроек двигателя..."); sender.SendCommandAsync(_targerAddressHost.TargetAddress, readSettingsCmd, _readSettingsTimeout, 2, (sendException, replyBytes) => { if (sendException != null) { var errorMessage = "Произошла ошибка во время чтения настрок двигателя"; _logger.Log(errorMessage); try { var ex = new Exception(errorMessage, sendException); _notifyWorker.AddWork(() => callback.Invoke(ex, null)); _notifyWorker.AddWork(() => FireEventEngineSettingsReadComplete(ex, null)); _notifyWorker.AddWork(() => _settingsStorageSettable.SetSettings(null)); } catch (Exception) { _logger.Log( "Не удалось совершить обратный вызов после неудачного чтения настроек двигателя (либо не удалось обnullить в хранилище)"); } return; } try { var result = readSettingsCmd.GetResult(replyBytes); try { _notifyWorker.AddWork(() => callback.Invoke(null, result)); _notifyWorker.AddWork(() => FireEventEngineSettingsReadComplete(null, result)); _notifyWorker.AddWork(() => _settingsStorageSettable.SetSettings(result)); _logger.Log("Настройки двигателя успешно прочитаны"); } catch { _logger.Log( "Не удалось совершить обратный вызов после успешного чтения настроек двигателя (либо не удалось сохранить настройки в хранилище)"); } } catch (Exception resultGetException) { var errorMessage = "Ошибка во время разбора ответа на команду чтения настроек двигателя: " + resultGetException.Message; _logger.Log(errorMessage); try { var ex = new Exception(errorMessage, resultGetException); _notifyWorker.AddWork(() => callback.Invoke(ex, null)); _notifyWorker.AddWork(() => FireEventEngineSettingsReadComplete(ex, null)); _notifyWorker.AddWork(() => _settingsStorageSettable.SetSettings(null)); } catch { _logger.Log( "Не удалось совершить обратный вызов после неудачного парсинга настроек двигателя (либо не удалось обnullить в хранилище)"); } } }); }
public void AddCommandToQueueAndExecuteAsync(object item, IoPriority priority) { _queueWorker.AddWork(() => { try { QueueLength++; NotifyQueueCountChanged(); IsTaskExecuting = true; if (item is QueueItem queueItem) { var addressItem = queueItem; var progressItemPart = new List <ISendResult>(); foreach (var sendItem in addressItem.SendingItems) { Exception exc = null; byte[] result = null; try { var lastBadTime = _linkQualityStorage.GetLastBadTime(sendItem.Address); var nowTime = DateTime.Now; if (lastBadTime.HasValue && nowTime - lastBadTime.Value < _onlineCheckTime) { exc = new Exception(lastBadTime.Value.ToString("yyyy.MM.dd-HH:mm:ss") + " с объектом по адресу " + sendItem.Address + " не получалось установить связь, так что еще рано с ним связываться (прошло времени: " + (nowTime - lastBadTime.Value).TotalSeconds.ToString("f2") + " сек, а должно пройти: " + _onlineCheckTime.TotalSeconds.ToString("f2") + " сек)"); } else { Log.Log("Запрос в сеть БУМИЗ для объекта по адресу" + sendItem.Address); result = AskForData(sendItem.Address, sendItem.Buffer, sendItem.AttemptsCount, sendItem.WaitTimeout); _linkQualityStorage.SetLastBadTime(sendItem.Address, null); Log.Log("Связь с объектом по адресу " + sendItem.Address + " была установлена, время последнего неудачного обмена обнулено"); } } catch (Exception ex) { var lastBadTime = DateTime.Now; _linkQualityStorage.SetLastBadTime(sendItem.Address, lastBadTime); exc = ex; Log.Log("Во время обмена произошла ошибка, поэтому время неудачного обмена установлено в значение: " + lastBadTime.ToString("yyyy.MM.dd-HH:mm:ss") + ", исключение: " + ex); } finally { progressItemPart.Add(new SendingResult(result, exc, sendItem)); } } _notifyWorker.AddWork(() => addressItem.OnComplete(progressItemPart)); } else if (item is IQueueRawItem) { Log.Log("Отправка произвольных данных в порт..."); var rawItem = item as IQueueRawItem; var result = new SendRawResultSimple(); try { result.Bytes = _channelSimple.RequestBytes(rawItem.SendItem.SendingBytes.ToArray(), rawItem.SendItem.AwaitedBytesCount, 10); } catch (Exception ex) { result.ChannelException = ex; } if (rawItem.OnSendComplete != null) { _notifyWorker.AddWork(() => rawItem.OnSendComplete(result)); } } } catch (Exception ex) { Log.Log("В задании для обработчика очереди обмена произошло исключение: " + ex); } finally { //Thread.Sleep(100); IsTaskExecuting = false; QueueLength--; NotifyQueueCountChanged(); } } , (int)priority); }
public void SendCommandAsync(byte address, IRrModbusCommandWithReply command, TimeSpan timeout, int maxAttemptsCount, Action <Exception, byte[]> onComplete) { _backWorker.AddWork(() => { Exception backgroundException = null; byte[] resultBytes = null; try { var cmdBytes = command.Serialize(); var sendBytes = new byte[cmdBytes.Length + 4]; // 1 byte address + 2 bytes CRC16 sendBytes[0] = address; sendBytes[1] = command.CommandCode; cmdBytes.CopyTo(sendBytes, 2); var sendCrc = MathExtensions.GetCrc16FromArray(sendBytes, 0, sendBytes.Length - 2); sendBytes[sendBytes.Length - 2] = sendCrc.Low; sendBytes[sendBytes.Length - 1] = sendCrc.High; RaiseCommandHeared(address, command.CommandCode, sendBytes); byte[] replyBytes = null; Exception lastException = null; for (var i = 0; i < maxAttemptsCount; ++i) { try { _portExtender.WriteBytes(sendBytes, 0, sendBytes.Length); replyBytes = _portExtender.ReadBytes(command.ReplyLength + 4, timeout, true); // + 4 bytes are: addr, cmd, crc, crc lastException = null; break; } catch (Exception ex) { lastException = ex; replyBytes = null; } } if (lastException != null) { throw lastException; } if (replyBytes != null) { // length is checked in port extender if (replyBytes[0] != address) { throw new Exception("Address is wrong"); } if (replyBytes[1] != command.CommandCode) { throw new Exception("Command code is wrong (" + replyBytes[1] + "), assumed the same as it was sended: " + command.CommandCode); } var crc = MathExtensions.GetCrc16FromArray(replyBytes, 0, replyBytes.Length - 2); if (crc.Low != replyBytes[replyBytes.Length - 2]) { throw new Exception("Crc Low byte is wrong, assumed to be 0x" + crc.Low.ToString("x2") + " (" + crc.Low + " dec)"); } if (crc.High != replyBytes[replyBytes.Length - 1]) { throw new Exception("Crc High byte is wrong, assumed to be 0x" + crc.High.ToString("x2") + " (" + crc.High + " dec)"); } resultBytes = new byte[replyBytes.Length - 4]; for (var i = 2; i < replyBytes.Length - 2; ++i) { resultBytes[i - 2] = replyBytes[i]; } RaiseCommandHeared(address, command.CommandCode, replyBytes); } else { throw new Exception("Внутренняя ошибка алгоритма, обратитесь к разработчикам"); } } catch (Exception ex) { backgroundException = ex; resultBytes = null; } finally { onComplete(backgroundException, resultBytes); } }); }
public void ReadSettingsAsync(byte zeroBasedAinNumber, bool forceRead, Action <Exception, IAinSettings> callback) { if (forceRead == false) { // Берем настройки АИН из хранилища: var settings = _ainSettingsStorageSettable.GetSettings(zeroBasedAinNumber); if (settings != null) { _notifyWorker.AddWork(() => callback.Invoke(null, settings)); // TODO: callback fail unknown, use try -> invoke, catch -> log return; } } // Вычитываем настройки из порта: var sender = _commandSenderHost.Sender; if (sender == null) { throw new NullReferenceException("Порт передачи данных не открыт"); } var readSettingsCmd = new ReadAinSettingsCommand(zeroBasedAinNumber); _logger.Log("Чтение настроек АИН " + (zeroBasedAinNumber + 1) + "..."); _notifyWorker.AddWork(() => FireEventAinSettingsReadStarted(zeroBasedAinNumber)); sender.SendCommandAsync(_targerAddressHost.TargetAddress, readSettingsCmd, _readSettingsTimeout, 2, (sendException, replyBytes) => { if (sendException != null) { var errorMessage = "Произошла ошибка во время чтения настрок АИН" + (zeroBasedAinNumber + 1); _logger.Log(errorMessage); try { var ex = new Exception(errorMessage, sendException); _notifyWorker.AddWork(() => callback.Invoke(ex, null)); _notifyWorker.AddWork(() => FireEventAinSettingsReadComplete(zeroBasedAinNumber, ex, null)); _notifyWorker.AddWork(() => _ainSettingsStorageSettable.SetSettings(zeroBasedAinNumber, null)); } catch { _logger.Log( "Не удалось совершить обратный вызов после неудачного чтения настроек (либо не удалось обnullить в хранилище) АИН" + (zeroBasedAinNumber + 1)); } return; } try { var result = readSettingsCmd.GetResult(replyBytes); if (zeroBasedAinNumber == 0 && result.Ain1LinkFault) { throw new Exception("Настройки АИН1 были считаны, однако флаг ошибки связи с АИН1 взведен"); } if (zeroBasedAinNumber == 1 && result.Ain2LinkFault) { throw new Exception("Настройки АИН2 были считаны, однако флаг ошибки связи с АИН2 взведен"); } if (zeroBasedAinNumber == 2 && result.Ain3LinkFault) { throw new Exception("Настройки АИН3 были считаны, однако флаг ошибки связи с АИН3 взведен"); } try { _notifyWorker.AddWork(() => callback.Invoke(null, result)); _notifyWorker.AddWork(() => FireEventAinSettingsReadComplete(zeroBasedAinNumber, null, result)); _notifyWorker.AddWork(() => _ainSettingsStorageSettable.SetSettings(zeroBasedAinNumber, result)); _logger.Log("Настройки АИН " + (zeroBasedAinNumber + 1) + " успешно прочитаны"); } catch { _logger.Log( "Не удалось совершить обратный вызов после успешного чтения настроек (либо не удалось сохранить настройки в хранилище) АИН" + (zeroBasedAinNumber + 1)); } } catch (Exception resultGetException) { var errorMessage = "Ошибка во время разбора ответа на команду чтения настроек АИН" + (zeroBasedAinNumber + 1) + ": " + resultGetException.Message; _logger.Log(errorMessage); try { var ex = new Exception(errorMessage, resultGetException); _notifyWorker.AddWork(() => callback.Invoke(ex, null)); _notifyWorker.AddWork(() => FireEventAinSettingsReadComplete(zeroBasedAinNumber, ex, null)); _notifyWorker.AddWork(() => _ainSettingsStorageSettable.SetSettings(zeroBasedAinNumber, null)); } catch { _logger.Log( "Не удалось совершить обратный вызов после неудачного парсинга настроек (либо не удалось обnullить в хранилище) АИН " + (zeroBasedAinNumber + 1)); } } }); }
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))); } } }); }
private void ReadCycle() { _logger.Log("Запуск циклического опроса телеметрии"); Cancel = false; _readingInProgress = true; _readCycleCommand.RaiseCanExecuteChanged(); _stopReadingCommand.RaiseCanExecuteChanged(); _backWorker.AddWork(() => { try { var w8er = new ManualResetEvent(false); while (!Cancel) { var cmd = new ReadCoolerTelemetryCommand(); _commandSenderHost.Sender.SendCommandAsync( 0x01, cmd, TimeSpan.FromSeconds(0.2), 2, (exception, bytes) => { ICoolerTelemetry coolerTelemetry = null; try { if (exception != null) { throw new Exception("Произошла ошибка во время обмена", exception); } var result = cmd.GetResult(bytes); coolerTelemetry = result; } catch (Exception ex) { // TODO: log exception, null values _logger.Log("Ошибка: " + ex.Message); Console.WriteLine(ex); } finally { _userInterfaceRoot.Notifier.Notify(() => CoolerTelemetryVm.UpdateTelemetry(coolerTelemetry)); w8er.Set(); } }); w8er.WaitOne(); w8er.Reset(); Thread.Sleep(300); // TODO: interval must be setted by user } } catch (Exception ex) { _logger.Log("Ошибка фонового потока очереди отправки: " + ex.Message); } finally { _logger.Log("Циклический опрос окончен"); _userInterfaceRoot.Notifier.Notify(() => { _readingInProgress = false; _readCycleCommand.RaiseCanExecuteChanged(); _stopReadingCommand.RaiseCanExecuteChanged(); }); } }); }
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); }); } }); }