Exemple #1
0
		void GetAllStates()
		{
			IsDBMissmatchDuringMonitoring = false;
			GKProgressCallback progressCallback = GKProcessorManager.StartProgress("Опрос объектов ГК", "", GkDatabase.Descriptors.Count, false, GKProgressClientType.Monitor);

			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Опрос состояний объектов"))
			{
				for (int i = 0; i < GkDatabase.Descriptors.Count; i++)
				{
					var descriptor = GkDatabase.Descriptors[i];
					gkLifecycleManager.Progress(i + 1, GkDatabase.Descriptors.Count);

					LastUpdateTime = DateTime.Now;
					GetState(descriptor.GKBase);
					if (!IsConnected)
					{
						break;
					}
					GKProcessorManager.DoProgress(descriptor.GKBase.DescriptorPresentationName, progressCallback);

					WaitIfSuspending();
					if (IsStopping)
						return;
				}
			}
			GKProcessorManager.StopProgress(progressCallback);

			CheckTechnologicalRegime();
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Передача состояний объектов"))
			{
				NotifyAllObjectsStateChanged();
				IsJournalAnyDBMissmatch = IsDBMissmatchDuringMonitoring;
			}
		}
		public bool ReadMissingJournalItems()
		{
			var gkIpAddress = GKManager.GetIpAddress(GkDatabase.RootDevice);
			var localLastDBNo = -1;
			using (var skdDatabaseService = new RubezhDAL.DataClasses.DbService())
			{
				localLastDBNo = skdDatabaseService.GKMetadataTranslator.GetLastJournalNo(gkIpAddress);
			}
			if (localLastDBNo == -1)
			{
				return true;
			}
			var remoteLastId = GetLastId();
			if (remoteLastId == -1)
			{
				return false;
			}
			using (var skdDatabaseService = new RubezhDAL.DataClasses.DbService())
			{
				skdDatabaseService.GKMetadataTranslator.SetLastJournalNo(gkIpAddress, remoteLastId);
			}
			if (remoteLastId > localLastDBNo)
			{
				if (remoteLastId - localLastDBNo > 1000)
					localLastDBNo = remoteLastId - 1000;

				var progressCallback = GKProcessorManager.StartProgress("Синхронизация журнала ГК " + gkIpAddress, "", remoteLastId - localLastDBNo, true, GKProgressClientType.Monitor);

				using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Синхронизация журнала"))
				{
					for (int index = localLastDBNo; index <= remoteLastId; index++)
					{
						gkLifecycleManager.Progress(index - localLastDBNo + 1, remoteLastId - localLastDBNo);

						LastUpdateTime = DateTime.Now;
						if (progressCallback.IsCanceled)
							break;

						WaitIfSuspending();
						if (IsStopping)
						{
							break;
						}

						var journaParser = ReadJournal(index);
						if (journaParser != null)
						{
							GKProcessorManager.DoProgress((index - localLastDBNo).ToString() + " из " + (remoteLastId - localLastDBNo).ToString(), progressCallback);
							AddJournalItem(journaParser.JournalItem);
						}
					}
				}

				GKProcessorManager.StopProgress(progressCallback);
				LastId = remoteLastId;
			}
			return true;
		}
Exemple #3
0
		public void Suspend()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Приостановка потока мониторинга"))
			{
				IsSuspending = true;
				if (StopEvent != null)
				{
					StopEvent.Set();
				}
				SetDescriptorsSuspending(true);
			}
		}
Exemple #4
0
		public void StartThread()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Запуск потока мониторинга"))
			{
				IsStopping = false;
				SetDescriptorsSuspending(false);
				if (RunThread == null)
				{
					StopEvent = new AutoResetEvent(false);
					RunThread = new Thread(OnRunThread);
					RunThread.Name = "GK Watcher " + GkDatabase.RootDevice.PresentationName;
					RunThread.Start();
				}
			}
		}
Exemple #5
0
		void PingJournal()
		{
			JournalParser journalParser;
			if (IsFirstTimeReadJournal && !String.IsNullOrEmpty(GkDatabase.RootDevice.GetReservedIpAddress())) // Находим последнее событие на КАУ первый раз (при запуске сервера)
			{
				journalParser = GetKauJournalById(-1);
				if (journalParser != null)
					LastKauId = journalParser.KauJournalRecordNo;
				IsFirstTimeReadJournal = false;
			}
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Проверка журнала"))
			{
				if (IpAddress != GkDatabase.RootDevice.GetGKIpAddress())
				{
					if (!String.IsNullOrEmpty(IpAddress))
					{
						var lastKauJournal = GetKauJournalById(LastKauId);
						if (lastKauJournal != null)
							LastId = lastKauJournal.GKJournalRecordNo;
					}
					IpAddress = GkDatabase.RootDevice.GetGKIpAddress();
				}
				var newLastId = GetLastId();
				if (newLastId == -1)
					return;
				if (LastId == -1)
					LastId = newLastId;
				if (newLastId > LastId)
				{
					for (int index = LastId + 1; index <= newLastId; index++)
					{
						gkLifecycleManager.Progress(index - LastId, newLastId - LastId);
						journalParser = ReadAndPublish(index);
						if (journalParser != null && journalParser.KauJournalRecordNo != 0)
							LastKauId = journalParser.KauJournalRecordNo;
					}
					LastId = newLastId;

					gkLifecycleManager.AddItem("Изменение индекса в БД");
					using (var skdDatabaseService = new RubezhDAL.DataClasses.DbService())
					{
						var gkIpAddress = GKManager.GetIpAddress(GkDatabase.RootDevice);
						skdDatabaseService.GKMetadataTranslator.SetLastJournalNo(gkIpAddress, LastId);
					}
				}
			}
		}
Exemple #6
0
		public void StopThread()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Остановка потока мониторинга"))
			{
				IsStopping = true;
				if (StopEvent != null)
				{
					StopEvent.Set();
				}
				if (RunThread != null)
				{
					RunThread.Join(TimeSpan.FromSeconds(5));
				}
				RunThread = null;
				SetDescriptorsSuspending(true);
			}
		}
Exemple #7
0
		public static bool GoToTechnologicalRegime(GKDevice device, GKProgressCallback progressCallback, Guid clientUID)
		{
			using (var gkLifecycleManager = new GKLifecycleManager(device, "Переход в технологический режим"))
			{
				if (IsInTechnologicalRegime(device))
					return true;

				GKProcessorManager.DoProgress(device.PresentationName + " Переход в технологический режим", progressCallback, clientUID);
				SendManager.Send(device, 0, 14, 0, null, device.DriverType == GKDriverType.GK || device.DriverType == GKDriverType.GKMirror);
				for (int i = 0; i < 10; i++)
				{
					if (progressCallback.IsCanceled)
						return false;
					if (IsInTechnologicalRegime(device))
						return true;
					Thread.Sleep(TimeSpan.FromSeconds(1));
				}

				return false;
			}
		}
		public void WriteFileToGK(GKDevice gkControllerDevice, Guid clientUID)
		{
			using (var gkLifecycleManager = new GKLifecycleManager(gkControllerDevice, "Запись файла в ГК"))
			{
				gkLifecycleManager.AddItem("Формирование хэша");
				var gkFileInfo = new GKFileInfo();
				gkFileInfo.Initialize(gkControllerDevice);
				var bytesList = new List<byte>();
				bytesList.AddRange(gkFileInfo.InfoBlock);
				bytesList.AddRange(gkFileInfo.FileBytes);

				gkLifecycleManager.AddItem("Перевод в режим записи файла");
				var sendResult = SendManager.Send(gkControllerDevice, 0, 21, 0);
				if (sendResult.HasError)
				{
					Error = "Невозможно начать процедуру записи ";
					gkLifecycleManager.AddItem("Ошибка");
					return;
				}

				var progressCallback = GKProcessorManager.StartProgress("Запись файла в " + gkControllerDevice.PresentationName, null, bytesList.Count / 256, false, GKProgressClientType.Administrator, clientUID);
				for (var i = 0; i < bytesList.Count; i += 256)
				{
					gkLifecycleManager.Progress(i + 1, bytesList.Count);
					GKProcessorManager.DoProgress("Запись блока данных " + i + 1, progressCallback, clientUID);

					var bytesBlock = BitConverter.GetBytes((uint)(i / 256 + 1)).ToList();
					bytesBlock.AddRange(bytesList.GetRange(i, Math.Min(256, bytesList.Count - i)));
					for (int j = 0; j < 10; j++)
					{
						sendResult = SendManager.Send(gkControllerDevice, (ushort)bytesBlock.Count(), 22, 0, bytesBlock);
						var result = sendResult.Bytes.Count > 0 && sendResult.Bytes[0] == 1;
						if (!sendResult.HasError && result)
							break;
						if (j == 9)
						{
							Error = "Невозможно записать блок данных " + i;
							gkLifecycleManager.AddItem("Ошибка");
							return;
						}
					}
				}
				gkLifecycleManager.AddItem("Запись последнего блока данных");
				var endBlock = BitConverter.GetBytes((uint)(bytesList.Count() / 256 + 1)).ToList();
				sendResult = SendManager.Send(gkControllerDevice, 0, 22, 0, endBlock);
				var endResult = sendResult.Bytes.Count > 0 && sendResult.Bytes[0] == 0;
				if (sendResult.HasError || !endResult)
				{
					Error = "Невозможно завершить запись файла ";
					gkLifecycleManager.AddItem("Ошибка");
				}
				var sendResultRead = SendManager.Send(gkControllerDevice, 4, 23, 256, new List<byte>(BitConverter.GetBytes(1)));
				if (!gkFileInfo.InfoBlock.SequenceEqual(sendResultRead.Bytes))
				{
					Error = "Не удалось корректно записать информационный блок ";
					gkLifecycleManager.AddItem("Ошибка");
				}
			}
		}
		public OperationResult<string> ReadConfigFileFromGK(GKDevice gkControllerDevice, GKProgressCallback progressCallback, Guid clientUID)
		{
			progressCallback = GKProcessorManager.StartProgress("Чтение конфигурационного файла из " + gkControllerDevice.PresentationName, "Проверка связи", 1, true, GKProgressClientType.Administrator, clientUID);
			try
			{
				using (var gkLifecycleManager = new GKLifecycleManager(gkControllerDevice, "Чтение файла ГК"))
				{
					gkLifecycleManager.AddItem("Чтение информационного блока");
					var gkFileInfo = ReadInfoBlock(gkControllerDevice);
					if (Error != null)
					{
						gkLifecycleManager.AddItem("Ошибка чтения информационного блока");
						return OperationResult<string>.FromError("Ошибка чтения информационного блока");
					}

					var allbytes = new List<byte>();
					uint i = 2;
					progressCallback = GKProcessorManager.StartProgress("Чтение конфигурационного файла из " + gkControllerDevice.PresentationName, "", (int)(gkFileInfo.FileSize / 256), true, GKProgressClientType.Administrator, clientUID);
					while (true)
					{
						if (progressCallback.IsCanceled)
							return OperationResult<string>.FromError("Операция отменена");
						GKProcessorManager.DoProgress("Чтение блока данных " + i, progressCallback, clientUID);
						gkLifecycleManager.Progress((int)i, (int)(gkFileInfo.FileSize / 256));

						var data = new List<byte>(BitConverter.GetBytes(i++));
						var sendResultBytesCount = 256;
						for (int j = 0; j < 10; j++)
						{
							var sendResult = SendManager.Send(gkControllerDevice, 4, 23, 256, data);
							allbytes.AddRange(sendResult.Bytes);
							sendResultBytesCount = sendResult.Bytes.Count();
							if (!sendResult.HasError)
								break;
							if (j == 9)
							{
								return OperationResult<string>.FromError("Невозможно прочитать блок данных " + i);
							}
						}
						if (sendResultBytesCount < 256)
							break;
					}
					if (allbytes.Count == 0)
						return OperationResult<string>.FromError("Конфигурационный файл отсутствует");

					var folderName = AppDataFolderHelper.GetFolder("TempServer");
					var configFileName = Path.Combine(folderName, "ConfigFromGK.fscp");
					if (Directory.Exists(folderName))
						Directory.Delete(folderName, true);
					Directory.CreateDirectory(folderName);
					var fileStream = new FileStream(configFileName, FileMode.CreateNew, FileAccess.ReadWrite);
					fileStream.Write(allbytes.ToArray(), 0, allbytes.Count);
					fileStream.Close();

					return new OperationResult<string>(configFileName);
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "GKDescriptorsWriter.WriteConfig");
				return OperationResult<string>.FromError("Непредвиденная ошибка");
			}
			finally
			{
				if (progressCallback != null)
					GKProcessorManager.StopProgress(progressCallback, clientUID);
			}
		}
Exemple #10
0
		public static bool GoToWorkingRegime(GKDevice device, GKProgressCallback progressCallback, Guid clientUID, bool waitUntillStart = true)
		{
			using (var gkLifecycleManager = new GKLifecycleManager(device, "Переход в рабочий режим"))
			{
				progressCallback.IsCanceled = false;
				GKProcessorManager.DoProgress(device.PresentationName + " Переход в рабочий режим", progressCallback, clientUID);
				if (progressCallback.IsCanceled)
					return true;
				SendManager.Send(device, 0, 11, 0, null, device.DriverType == GKDriverType.GK || device.DriverType == GKDriverType.GKMirror);

				if (waitUntillStart)
				{
					for (int i = 0; i < 20; i++)
					{
						if (progressCallback.IsCanceled)
							return true;
						var sendResult = Ping(device);
						if (!sendResult.HasError)
						{
							if (sendResult.Bytes.Count > 0)
							{
								var version = sendResult.Bytes[0];
								if (version <= 127)
								{
									return true;
								}
							}
						}
						Thread.Sleep(TimeSpan.FromSeconds(1));
					}
					return false;
				}
				else
				{
					return true;
				}
			}
		}
Exemple #11
0
		bool FindDevicesOnShleif(GKDevice kauDevice, int shleifNo, GKProgressCallback progressCallback, Guid clientUID)
		{
			var shleifDevice = kauDevice.Children.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_KAU_Shleif && x.IntAddress == shleifNo + 1);
			progressCallback.Title = "Автопоиск на АЛС " + (shleifNo + 1) + " устройства " + kauDevice.PresentationName;
			progressCallback.CurrentStep = 0;
			progressCallback.StepCount = 256;
			using (var gkLifecycleManager = new GKLifecycleManager(kauDevice, "Автопоиск на АЛС " + (shleifNo + 1)))
			{
				var deviceGroups = new List<DeviceGroup>();
				var devices = new List<GKDevice>();
				for (int address = 1; address <= 255; address++)
				{
					gkLifecycleManager.Progress(address, 255);
					GKProcessorManager.DoProgress("Поиск устройства с адресом " + address, progressCallback, clientUID);
					if (progressCallback.IsCanceled)
					{
						Error = "Операция отменена";
						return false;
					}
					var bytes = new List<byte>();
					bytes.Add(0);
					bytes.Add((byte)address);
					bytes.Add((byte)shleifNo);
					var result2 = new SendResult("");
					for (int i = 0; i < 3; i++)
					{
						if (progressCallback.IsCanceled)
						{
							Error = "Операция отменена";
							return false;
						}
						result2 = SendManager.Send(kauDevice, 3, 0x86, 6, bytes, true, false, 3000);
						if (!result2.HasError)
							break;
					}
					if (!result2.HasError)
					{
						if (result2.Bytes.Count == 6)
						{
							var driverTypeNo = result2.Bytes[1];
							var serialNo = BytesHelper.SubstructInt(result2.Bytes, 2);
							var driver = GKManager.Drivers.FirstOrDefault(x => x.DriverTypeNo == (ushort)driverTypeNo);
							if (driver != null)
							{
								var device = new GKDevice();
								device.Driver = driver;
								device.DriverUID = driver.UID;
								device.IntAddress = (byte)address;
								devices.Add(device);

								var deviceGroup = deviceGroups.FirstOrDefault(x => x.SerialNo == serialNo);
								if (deviceGroup == null || (serialNo == 0 || serialNo == -1) || (driver.DriverType != GKDriverType.RSR2_AM_1 && driver.DriverType != GKDriverType.RSR2_MAP4
									&& driver.DriverType != GKDriverType.RSR2_MVK8 && driver.DriverType != GKDriverType.RSR2_RM_1 && driver.DriverType != GKDriverType.RSR2_OPKZ))
								{
									deviceGroup = new DeviceGroup();
									deviceGroup.SerialNo = serialNo;
									deviceGroups.Add(deviceGroup);
								}
								deviceGroup.Devices.Add(device);
							}
						}
					}
					else
					{
						break;
					}
				}

				foreach (var deviceGroup in deviceGroups)
				{
					var firstDeviceInGroup = deviceGroup.Devices.FirstOrDefault();
					if (deviceGroup.Devices.Count > 1 && firstDeviceInGroup != null)
					{
						GKDriver groupDriver = null;
						if (firstDeviceInGroup.Driver.DriverType == GKDriverType.RSR2_AM_1)
						{
							if (deviceGroup.Devices.Count == 2)
								groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_AM_2);
							else
								groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_AM_4);
						}
						if (firstDeviceInGroup.Driver.DriverType == GKDriverType.RSR2_MAP4)
						{
							groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_MAP4_Group);
						}
						if (firstDeviceInGroup.Driver.DriverType == GKDriverType.RSR2_MVK8)
						{
							groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_MVK8_Group);
						}
						if (firstDeviceInGroup.Driver.DriverType == GKDriverType.RSR2_RM_1)
						{
							if (deviceGroup.Devices.Count == 2)
								groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_RM_2);
							else
								groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_RM_4);
						}
						if (firstDeviceInGroup.Driver.DriverType == GKDriverType.RSR2_OPKS)
						{
							groupDriver = GKManager.Drivers.FirstOrDefault(x => x.DriverType == GKDriverType.RSR2_OPSZ);
						}

						var groupDevice = new GKDevice();
						groupDevice.Driver = groupDriver;
						if (groupDriver != null)
							groupDevice.DriverUID = groupDriver.UID;
						groupDevice.IntAddress = firstDeviceInGroup.IntAddress;
						foreach (var deviceInGroup in deviceGroup.Devices)
						{
							groupDevice.Children.Add(deviceInGroup);
						}
						if (shleifDevice != null)
							shleifDevice.Children.Add(groupDevice);
					}
					else
					{
						if (shleifDevice != null)
							shleifDevice.Children.Add(firstDeviceInGroup);
					}
				}
			}
			return true;
		}
Exemple #12
0
		public void Resume()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Возобновление потока мониторинга"))
			{
				IsSuspending = false;
				SuspendingEvent.Set();
				SetDescriptorsSuspending(false);
			}
		}
Exemple #13
0
		void RunMonitoring()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Цикл мониторинга"))
			{
				gkLifecycleManager.AddItem("Проверка лицензии");
				var hasLicense = LicenseManager.CurrentLicenseInfo.LicenseMode != LicenseMode.NoLicense;
				if (HasLicense != hasLicense)
				{
					HasLicense = hasLicense;
					foreach (var descriptor in GkDatabase.Descriptors)
					{
						descriptor.GKBase.InternalState.IsNoLicense = !HasLicense;
					}
					NotifyAllObjectsStateChanged();
				}
				if (!hasLicense)
					return;

				if (WatcherManager.IsConfigurationReloading)
				{
					if ((DateTime.Now - WatcherManager.LastConfigurationReloadingTime).TotalSeconds > 100)
						WatcherManager.IsConfigurationReloading = false;
				}
				if (WatcherManager.IsConfigurationReloading)
					return;

				if (IsDBMissmatchDuringMonitoring)
				{
					if ((DateTime.Now - LastMissmatchCheckTime).TotalSeconds > 60)
					{
						gkLifecycleManager.AddItem("Ошибка сопоставления конфигурации. Опрос объектов");
						GetAllStates();
						LastMissmatchCheckTime = DateTime.Now;
					}
					return;
				}

				try
				{
					if (MustCheckTechnologicalRegime)
					{
						if ((DateTime.Now - LastTechnologicalRegimeCheckTime).TotalSeconds > 10)
						{
							LastTechnologicalRegimeCheckTime = DateTime.Now;
							CheckTechnologicalRegime();
							NotifyAllObjectsStateChanged();

							TechnologicalRegimeCheckCount++;
							if (TechnologicalRegimeCheckCount >= 10)
								MustCheckTechnologicalRegime = false;
						}
					}
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread CheckTechnologicalRegime");
				}

				try
				{
					gkLifecycleManager.AddItem("Проверка задач");
					CheckTasks();
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread CheckTasks");
				}

				try
				{
					gkLifecycleManager.AddItem("Проверка задержек");
					CheckDelays();
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread CheckDelays");
				}

				try
				{
					PingJournal();
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread PingJournal");
				}

				try
				{
					gkLifecycleManager.AddItem("Проверка измерений");
					CheckMeasure();
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread CheckMeasure");
				}

				try
				{
					if ((DateTime.Now - LastKAUMeasureTime) > TimeSpan.FromHours(1))
					{
						LastKAUMeasureTime = DateTime.Now;
						gkLifecycleManager.AddItem("Измерение токопотребления");
						CheckKAUMeasure();
					}
				}
				catch (Exception e)
				{
					Logger.Error(e, "Watcher.OnRunThread CheckKAUMeasure");
				}
			}
		}
Exemple #14
0
		bool InitializeMonitoring()
		{
			bool IsPingFailure = false;
			bool IsInTechnologicalRegime = false;
			bool IsGetStatesFailure = false;
			IsHashFailure = false;

			foreach (var descriptor in GkDatabase.Descriptors)
			{
				descriptor.GKBase.InternalState.Clear();
			}

			while (true)
			{
				LastUpdateTime = DateTime.Now;
				GKCallbackResult = new GKCallbackResult();
				foreach (var descriptor in GkDatabase.Descriptors)
				{
					descriptor.GKBase.InternalState.IsInitialState = true;
				}

				using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Проверка связи"))
				{
					var deviceInfo = DeviceBytesHelper.GetDeviceInfo(GkDatabase.RootDevice);
					var pingResult = string.IsNullOrEmpty(deviceInfo);
					if (IsPingFailure != pingResult)
					{
						GKCallbackResult = new GKCallbackResult();
						IsPingFailure = pingResult;
						if (IsPingFailure)
							AddFailureJournalItem(JournalEventNameType.Нет_связи_с_ГК, JournalEventDescriptionType.Старт_мониторинга);
						else
							AddFailureJournalItem(JournalEventNameType.Связь_с_ГК_восстановлена, JournalEventDescriptionType.Старт_мониторинга);

						foreach (var descriptor in GkDatabase.Descriptors)
						{
							descriptor.GKBase.InternalState.IsConnectionLost = IsPingFailure;
							descriptor.GKBase.InternalState.IsInitialState = !IsPingFailure;
						}
						NotifyAllObjectsStateChanged();
						OnGKCallbackResult(GKCallbackResult);
					}

					if (IsPingFailure)
					{
						gkLifecycleManager.SetError("Ошибка");
						if (ReturnAfterWait(5000))
							return false;
						continue;
					}
				}

				var result = CheckTechnologicalRegime();
				if (IsInTechnologicalRegime != result)
				{
					GKCallbackResult = new GKCallbackResult();
					IsInTechnologicalRegime = result;
					if (IsInTechnologicalRegime)
						AddFailureJournalItem(JournalEventNameType.ГК_в_технологическом_режиме, "Старт мониторинга");
					else
						AddFailureJournalItem(JournalEventNameType.ГК_в_рабочем_режиме, "Старт мониторинга");

					NotifyAllObjectsStateChanged();
					OnGKCallbackResult(GKCallbackResult);
				}

				if (IsInTechnologicalRegime)
				{
					GKLifecycleManager.Add(GkDatabase.RootDevice, "Устройство в технологическом режиме");
					if (ReturnAfterWait(5000))
						return false;
					continue;
				}

				using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Запрос хэша"))
				{
					var hashResult = GetHashResult();

					if (IsHashFailure != hashResult.Item1)
					{
						GKCallbackResult = new GKCallbackResult();
						IsHashFailure = hashResult.Item1;
						if (IsHashFailure)
							AddFailureJournalItem(JournalEventNameType.Конфигурация_прибора_не_соответствует_конфигурации_ПК, JournalEventDescriptionType.Не_совпадает_хэш);
						else
							AddFailureJournalItem(JournalEventNameType.Конфигурация_прибора_соответствует_конфигурации_ПК, JournalEventDescriptionType.Совпадает_хэш);

						foreach (var descriptor in GkDatabase.Descriptors)
						{
							descriptor.GKBase.InternalState.IsDBMissmatch = IsHashFailure;
							descriptor.GKBase.InternalState.IsInitialState = false;
						}
						NotifyAllObjectsStateChanged();
						OnGKCallbackResult(GKCallbackResult);
					}

					if (IsHashFailure)
					{
						gkLifecycleManager.SetError(hashResult.Item2 == null ? "Ошибка" : "Не совпадает хэш");
						if (ReturnAfterWait(5000))
							return false;
						continue;
					}
				}

				GKCallbackResult = new GKCallbackResult();
				if (!ReadMissingJournalItems())
					AddFailureJournalItem(JournalEventNameType.Ошибка_при_синхронизации_журнала);
				OnGKCallbackResult(GKCallbackResult);

				GKCallbackResult = new GKCallbackResult();
				GetAllStates();
				result = IsDBMissmatchDuringMonitoring || !IsConnected;
				if (IsGetStatesFailure != result)
				{
					IsGetStatesFailure = result;
					if (IsGetStatesFailure)
						AddFailureJournalItem(JournalEventNameType.Ошибка_при_опросе_состояний_компонентов_ГК, DBMissmatchDuringMonitoringReason);
					else
						AddFailureJournalItem(JournalEventNameType.Устранена_ошибка_при_опросе_состояний_компонентов_ГК);
				}
				using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Передача состояний объектов"))
				{
					OnGKCallbackResult(GKCallbackResult);
				}

				if (IsGetStatesFailure)
				{
					GKLifecycleManager.Add(GkDatabase.RootDevice, "Ошибки при опросе состояний объектов");
					if (ReturnAfterWait(5000))
						return false;
					continue;
				}

				using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Передача состояний объектов"))
				{
					GKCallbackResult = new GKCallbackResult();
					foreach (var descriptor in GkDatabase.Descriptors)
					{
						descriptor.GKBase.InternalState.IsInitialState = false;
					}
					NotifyAllObjectsStateChanged();
					OnGKCallbackResult(GKCallbackResult);
				}

				return true;
			}
		}
		bool WriteConfigToDevice(CommonDatabase commonDatabase, GKProgressCallback progressCallback, Guid clientUID)
		{
			using (var gkLifecycleManager = new GKLifecycleManager(commonDatabase.RootDevice, "Запись дескрипторов"))
			{
				for (int descriptorNo = 0; descriptorNo < commonDatabase.Descriptors.Count; descriptorNo++)
				{
					var descriptor = commonDatabase.Descriptors[descriptorNo];
					gkLifecycleManager.Progress(descriptorNo + 1, commonDatabase.Descriptors.Count);
					var progressStage = commonDatabase.RootDevice.PresentationName + ": запись " + descriptor.GKBase.PresentationName + " " + "(" + descriptor.GetDescriptorNo() + ")" + " из " + commonDatabase.Descriptors.Count;
					GKProcessorManager.DoProgress(progressStage, progressCallback, clientUID);

					var packs = CreateDescriptors(descriptor);
					foreach (var pack in packs)
					{
						for (int i = 0; i < 10; i++)
						{
							var sendResult = SendManager.Send(commonDatabase.RootDevice, (ushort)(pack.Count), 17, 0, pack);
							if (sendResult.HasError)
							{
								if (i >= 9)
								{
									GKProcessorManager.StopProgress(progressCallback, clientUID);
									gkLifecycleManager.AddItem("Ошибка");
									return false;
								}
							}
							else
								break;
						}
					}
				}
				GKProcessorManager.DoProgress(commonDatabase.RootDevice.PresentationName + " Запись завершающего дескриптора", progressCallback, clientUID);
				WriteEndDescriptor(commonDatabase);
				return true;
			}
		}
Exemple #16
0
		public static bool EraseDatabase(GKDevice device, GKProgressCallback progressCallback, Guid clientUID)
		{
			using (var gkLifecycleManager = new GKLifecycleManager(device, "Стирание базы данных"))
			{
				GKProcessorManager.DoProgress(device.PresentationName + " Стирание базы данных", progressCallback, clientUID);
				for (int i = 0; i < 3; i++)
				{
					if (progressCallback.IsCanceled)
						return false;
					var sendResult = SendManager.Send(device, 0, 15, 0, null, true, false, 10000);
					if (!sendResult.HasError)
					{
						return true;
					}
					else
					{
						Thread.Sleep(TimeSpan.FromSeconds(1));
					}
				}
				return false;
			}
		}
		public void WriteConfig(GKDevice gkControllerDevice, GKProgressCallback progressCallback, Guid clientUID)
		{
			Errors = new List<string>();

			progressCallback = GKProcessorManager.StartProgress("Запись конфигурации", "Проверка связи", 1, false, GKProgressClientType.Administrator, clientUID);
			try
			{
				var gkDatabase = DescriptorsManager.GkDatabases.FirstOrDefault(x => x.RootDevice.UID == gkControllerDevice.UID);
				if (gkDatabase != null)
				{
					var kauDatabases = new List<KauDatabase>();
					var lostKauDatabases = new List<KauDatabase>();
					using (var gkLifecycleManager = new GKLifecycleManager(gkDatabase.RootDevice, "Проверка связи"))
					{
						gkLifecycleManager.AddItem("ГК");
						var pingResult = DeviceBytesHelper.Ping(gkDatabase.RootDevice);
						if (pingResult.HasError)
						{
							Errors.Add("Устройство " + gkDatabase.RootDevice.PresentationName + " недоступно");
							return;
						}

						foreach (var kauDatabase in gkDatabase.KauDatabases)
						{
							gkLifecycleManager.AddItem(kauDatabase.RootDevice.PresentationName);
							pingResult = DeviceBytesHelper.Ping(kauDatabase.RootDevice);
							if (!pingResult.HasError)
							{
								kauDatabases.Add(kauDatabase);
							}
							else
							{
								lostKauDatabases.Add(kauDatabase);
							}
						}
					}

					for (int i = 0; i < 3; i++)
					{
						Errors = new List<string>();

						var summaryDescriptorsCount = 4 + gkDatabase.Descriptors.Count;
						kauDatabases.ForEach(x => { summaryDescriptorsCount += 3 + x.Descriptors.Count; });

						var title = "Запись конфигурации в " + gkDatabase.RootDevice.PresentationName + (i > 0 ? " Попытка " + (i + 1) : "");
						progressCallback = GKProcessorManager.StartProgress(title, "", summaryDescriptorsCount, false, GKProgressClientType.Administrator, clientUID);
						var result = DeviceBytesHelper.GoToTechnologicalRegime(gkDatabase.RootDevice, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось перевести " + gkControllerDevice.PresentationName + " в технологический режим\nУстройство не доступно, либо вашего IP адреса нет в списке разрешенного адреса ГК");
							continue;
						}

						result = DeviceBytesHelper.EraseDatabase(gkDatabase.RootDevice, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось стереть базу данных ГК");
							continue;
						}

						foreach (var kauDatabase in kauDatabases)
						{
							result = DeviceBytesHelper.GoToTechnologicalRegime(kauDatabase.RootDevice, progressCallback, clientUID);
							if (!result)
							{
								Errors.Add("Не удалось перевести КАУ в технологический режим");
								continue;
							}

							if (!DeviceBytesHelper.EraseDatabase(kauDatabase.RootDevice, progressCallback, clientUID))
							{
								Errors.Add("Не удалось стереть базу данных КАУ");
								continue;
							}

							if (!WriteConfigToDevice(kauDatabase, progressCallback, clientUID))
							{
								Errors.Add("Не удалось записать дескриптор КАУ");
							}
						}

						result = WriteConfigToDevice(gkDatabase, progressCallback, clientUID);
						if (!result)
						{
							Errors.Add("Не удалось записать дескриптор ГК");
							continue;
						}


						var gkFileReaderWriter = new GKFileReaderWriter();
						gkFileReaderWriter.WriteFileToGK(gkControllerDevice, clientUID);
						if (gkFileReaderWriter.Error != null)
						{
							Errors.Add(gkFileReaderWriter.Error);
							break;
						}

						foreach (var kauDatabase in kauDatabases)
						{
							if (!DeviceBytesHelper.GoToWorkingRegime(kauDatabase.RootDevice, progressCallback, clientUID, kauDatabase.RootDevice.Driver.IsKau))
							{
								Errors.Add("Не удалось перевести " + kauDatabase.RootDevice.PresentationName + " в рабочий режим");
							}
						}

						if (!DeviceBytesHelper.GoToWorkingRegime(gkDatabase.RootDevice, progressCallback, clientUID, false))
						{
							Errors.Add("Не удалось перевести " + gkDatabase.RootDevice + " в рабочий режим");
						}
						break;
					}

					foreach (var kauDatabase in lostKauDatabases)
					{
						Errors.Add("Устройство " + kauDatabase.RootDevice.PresentationName + " недоступно");
					}
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "GKDescriptorsWriter.WriteConfig");
				Errors.Add(e.Message);
			}
			finally
			{
				if (progressCallback != null)
					GKProcessorManager.StopProgress(progressCallback, clientUID);
			}
		}
Exemple #18
0
		bool CheckTechnologicalRegime()
		{
			using (var gkLifecycleManager = new GKLifecycleManager(GkDatabase.RootDevice, "Проверка технологического режима"))
			{
				gkLifecycleManager.AddItem(GkDatabase.RootDevice.PresentationName);
				var isInTechnologicalRegime = DeviceBytesHelper.IsInTechnologicalRegime(GkDatabase.RootDevice);
				gkLifecycleManager.AddItem("Обновление состояний технологического режима");
				foreach (var descriptor in GkDatabase.Descriptors)
				{
					descriptor.GKBase.InternalState.IsInTechnologicalRegime = isInTechnologicalRegime;
				}

				if (!isInTechnologicalRegime)
				{
					foreach (var kauDatabase in GkDatabase.KauDatabases)
					{
						gkLifecycleManager.AddItem(kauDatabase.RootDevice.PresentationName);
						var isKAUInTechnologicalRegime = DeviceBytesHelper.IsInTechnologicalRegime(kauDatabase.RootDevice);
						gkLifecycleManager.AddItem("Обновление состояний технологического режима");
						foreach (var device in kauDatabase.RootDevice.AllChildrenAndSelf)
						{
							device.InternalState.IsInTechnologicalRegime = isKAUInTechnologicalRegime;
						}
					}
				}
				return isInTechnologicalRegime;
			}
		}