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; }
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); } } } }
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; } }
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); } }
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; }