void OnGKProgressCallbackEvent(GKProgressCallback gkProgressCallback, Guid? callbackUID) { ApplicationService.Invoke(() => { switch (gkProgressCallback.GKProgressCallbackType) { case GKProgressCallbackType.Start: if (gkProgressCallback.GKProgressClientType == GKProgressClientType.Monitor) { LoadingService.Show(gkProgressCallback.Title, gkProgressCallback.Text, gkProgressCallback.StepCount, gkProgressCallback.CanCancel); } return; case GKProgressCallbackType.Progress: if (gkProgressCallback.GKProgressClientType == GKProgressClientType.Monitor) { LoadingService.DoStep(gkProgressCallback.Text, gkProgressCallback.Title, gkProgressCallback.StepCount, gkProgressCallback.CurrentStep, gkProgressCallback.CanCancel); if (LoadingService.IsCanceled) ClientManager.RubezhService.CancelGKProgress(gkProgressCallback.UID, ClientManager.CurrentUser.Name); } return; case GKProgressCallbackType.Stop: LoadingService.Close(); return; } }); }
public OperationResult<bool> GKWriteConfiguration(Guid clientUID, Guid deviceUID) { var device = GKManager.Devices.FirstOrDefault(x => x.UID == deviceUID); if (device != null) { var progressCallback = new GKProgressCallback(); ServerTaskRunner.Add(progressCallback, "Запись конфигурации ГК", (() => { if (GKManager.DeviceConfiguration.OnlyGKDeviceConfiguration) { var deviceConfigFileName = AppDataFolderHelper.GetServerAppDataPath("Config" + Path.DirectorySeparatorChar + "GKDeviceConfiguration.xml"); var zipDeviceConfigFileName = AppDataFolderHelper.GetServerAppDataPath("GKDeviceConfiguration.fscp"); if (File.Exists(zipDeviceConfigFileName)) File.Delete(zipDeviceConfigFileName); var zipFile = new ZipFile(zipDeviceConfigFileName); zipFile.AddFile(deviceConfigFileName, ""); zipFile.Save(zipDeviceConfigFileName); zipFile.Dispose(); } var result = GKProcessorManager.GKWriteConfiguration(device, GetUserName(clientUID), progressCallback, clientUID); NotifyOperationResult_WriteConfiguration(result, clientUID); } )); return new OperationResult<bool>(true); } return OperationResult<bool>.FromError("Не найдено устройство в конфигурации. Предварительно необходимо применить конфигурацию"); }
static void OnGKCallbackResult(GKProgressCallback gkProgressCallback, Guid? clientUID) { GKProgressCallbacks.RemoveAll(x => x.IsCanceled && (DateTime.Now - x.CancelizationDateTime).TotalMinutes > 5); if (gkProgressCallback.GKProgressCallbackType == GKProgressCallbackType.Stop || !gkProgressCallback.IsCanceled) { if (GKProgressCallbackEvent != null) GKProgressCallbackEvent(gkProgressCallback, clientUID); } }
public static void StopProgress(GKProgressCallback progressCallback, Guid? clientUID = null) { var gkProgressCallback = new GKProgressCallback { UID = progressCallback.UID, LastActiveDateTime = DateTime.Now, GKProgressCallbackType = GKProgressCallbackType.Stop, GKProgressClientType = progressCallback.GKProgressClientType }; GKProgressCallbacks.Remove(gkProgressCallback); OnGKCallbackResult(gkProgressCallback, clientUID); }
public string Update(GKDevice device, List<byte> firmWareBytes, string userName, Guid clientUID) { GKProcessorManager.AddGKMessage(JournalEventNameType.Обновление_ПО_прибора, JournalEventDescriptionType.NULL, "", device, userName); ProgressCallback = GKProcessorManager.StartProgress("Обновление прошивки " + device.PresentationName, "", firmWareBytes.Count / 256, false, GKProgressClientType.Administrator, clientUID); GKProcessorManager.DoProgress("Проверка связи " + device.PresentationName, ProgressCallback, clientUID); if (DeviceBytesHelper.Ping(device).HasError) { return "Устройство " + device.PresentationName + " недоступно"; } if (!DeviceBytesHelper.GoToTechnologicalRegime(device, ProgressCallback, clientUID)) { return "Не удалось перевести " + device.PresentationName + " в технологический режим\n" + "Устройство не доступно, либо вашего IP адреса нет в списке разрешенного адреса ГК"; } GKProcessorManager.DoProgress("Удаление программы " + device.PresentationName, ProgressCallback, clientUID); if (!Clear(device)) { return "Устройство " + device.PresentationName + " недоступно"; } var data = new List<byte>(); var offset = 0; if (device.Driver.IsKau) offset = 0x10000; for (int i = 0; i < firmWareBytes.Count; i = i + 0x100) { GKProcessorManager.DoProgress("Запись блока данных " + i / 0x100 + 1, ProgressCallback, clientUID); data = new List<byte>(BitConverter.GetBytes(i + offset)); data.AddRange(firmWareBytes.GetRange(i, 0x100)); for (int j = 0; j < 10; j++) { var result = SendManager.Send(device, 260, 0x12, 0, data, true, false, 10000); if (!result.HasError) break; if (j == 9) { return "В заданное времени не пришел ответ от устройства"; } } } if (!DeviceBytesHelper.GoToWorkingRegime(device, ProgressCallback, clientUID)) { return "Не удалось перевести " + device.PresentationName + " в рабочий режим\n" + "Устройство не доступно, либо вашего " + "IP адреса нет в списке разрешенного адреса ГК"; } return null; }
public static void NotifyGKProgress(GKProgressCallback gkProgressCallback, Guid? clientUID) { var callbackResult = new CallbackResult() { CallbackResultType = CallbackResultType.GKProgress, GKProgressCallback = gkProgressCallback }; ClientType? clientType = null; if (gkProgressCallback != null) clientType = gkProgressCallback.GKProgressClientType == GKProgressClientType.Administrator ? ClientType.Administrator : ClientType.Monitor | ClientType.OPC | ClientType.WebService | ClientType.Other; CallbackManager.Add(callbackResult, clientType, clientUID); }
public static GKProgressCallback StartProgress(string title, string text, int stepCount, bool canCancel, GKProgressClientType progressClientType, Guid? clientUID = null) { var gkProgressCallback = new GKProgressCallback { GKProgressCallbackType = GKProgressCallbackType.Start, Title = title, Text = text, StepCount = stepCount, CanCancel = canCancel, GKProgressClientType = progressClientType }; GKProgressCallbacks.Add(gkProgressCallback); OnGKCallbackResult(gkProgressCallback, clientUID); return gkProgressCallback; }
public OperationResult<bool> GKReadConfigurationFromGKFile(Guid clientUID, Guid deviceUID) { var device = GKManager.Devices.FirstOrDefault(x => x.UID == deviceUID); if (device != null) { var progressCallback = new GKProgressCallback(); ServerTaskRunner.Add(progressCallback, "Чтение файла конфигурации ГК", new Action(() => { var result = GKProcessorManager.GKReadConfigurationFromGKFile(device, GetUserName(clientUID), progressCallback, clientUID); RubezhService.NotifyOperationResult_ReadConfigurationFromGKFile(result, clientUID); } )); return new OperationResult<bool>(true); } return OperationResult<bool>.FromError("Не найдено устройство в конфигурации. Предварительно необходимо применить конфигурацию"); }
public static void DoProgress(string text, GKProgressCallback progressCallback, Guid? clientUID = null) { progressCallback.CurrentStep++; var gkProgressCallback = new GKProgressCallback { UID = progressCallback.UID, LastActiveDateTime = DateTime.Now, GKProgressCallbackType = GKProgressCallbackType.Progress, Title = progressCallback.Title, Text = text, StepCount = progressCallback.StepCount, CurrentStep = progressCallback.CurrentStep, CanCancel = progressCallback.CanCancel, GKProgressClientType = progressCallback.GKProgressClientType }; OnGKCallbackResult(gkProgressCallback, clientUID); }
void ReadConfiguration(GKDevice gkControllerDevice, GKProgressCallback progressCallback, Guid clientUID) { var gkFileReaderWriter = new GKFileReaderWriter(); var gkFileInfo = gkFileReaderWriter.ReadInfoBlock(gkControllerDevice); if (gkFileReaderWriter.Error != null) { Error = gkFileReaderWriter.Error; GKProcessorManager.StopProgress(progressCallback, clientUID); return; } progressCallback = GKProcessorManager.StartProgress("Чтение конфигурации " + gkControllerDevice.PresentationName, "", gkFileInfo.DescriptorsCount, true, GKProgressClientType.Administrator, clientUID); ushort descriptorNo = 0; while (true) { if (progressCallback.IsCanceled) { Error = "Операция отменена"; break; } descriptorNo++; GKProcessorManager.DoProgress("Чтение базы данных объектов ГК " + descriptorNo, progressCallback, clientUID); const byte packNo = 1; var data = new List<byte>(BitConverter.GetBytes(descriptorNo)) { packNo }; for (int i = 0; i < 3; i++) { var sendResult = SendManager.Send(gkControllerDevice, 3, 19, ushort.MaxValue, data); var bytes = sendResult.Bytes; if (!sendResult.HasError && bytes.Count >= 5) { if (bytes[3] == 0xff && bytes[4] == 0xff) return; if (!Parse(bytes.Skip(3).ToList(), descriptorNo)) return; break; } if (i == 2) { Error = "Возникла ошибка при чтении объекта " + descriptorNo; return; } } } }
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 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); } }
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; } }
/// <summary> /// Возвращает число удалённых пропусков /// </summary> /// <param name="device"></param> /// <param name="usersCount"></param> /// <param name="progressCallback"></param> /// <returns></returns> static OperationResult<int> RemoveAllUsersInternal(GKDevice device, int usersCount, GKProgressCallback progressCallback = null) { progressCallback = GKProcessorManager.StartProgress("Удаление пользователей", "", usersCount, true, GKProgressClientType.Administrator); int cardsCount = 0; for (ushort i = 1; i <= usersCount; i++) { var user = new GKUser { Fio = "-", IsActive = false, Password = 1, GkNo = i, UserType = GKCardType.Operator, }; var removeResult = AddOrEditUser(user, device, false); if (!removeResult.HasError) cardsCount++; if (progressCallback != null) { GKProcessorManager.DoProgress("Пользователь " + i, progressCallback); if (progressCallback.IsCanceled) return OperationResult<int>.FromError("Операция отменена", cardsCount); } } GKProcessorManager.StopProgress(progressCallback); return new OperationResult<int>(cardsCount); }
public static OperationResult<bool> RewritePmfUsers(Guid clientUid, Guid deviceUID, List<GKUser> users, GKProgressCallback progressCallback) { var device = GKManager.Devices.FirstOrDefault(x => x.UID == deviceUID); if (device != null) { var getUsersCountResult = GetUsersCount(device, progressCallback); if (getUsersCountResult.HasError) return OperationResult<bool>.FromError(getUsersCountResult.Error); var oldUsersCount = getUsersCountResult.Result; var removeAllUsersInternalResult = RemoveAllUsersInternal(device, oldUsersCount, progressCallback); if (removeAllUsersInternalResult.HasError) return OperationResult<bool>.FromError(removeAllUsersInternalResult.Error); progressCallback = GKProcessorManager.StartProgress("Запись пользователей", "", users.Count, true, GKProgressClientType.Administrator); ushort gkNo = 1; foreach (var user in users.OrderBy(x => x.Password)) { user.GkNo = gkNo++; user.IsActive = true; AddOrEditUser(user, device, gkNo > oldUsersCount + 1); if (progressCallback.IsCanceled) { return OperationResult<bool>.FromError("Операция отменена"); } GKProcessorManager.DoProgress("Пользователь " + gkNo, progressCallback); } GKProcessorManager.StopProgress(progressCallback); return new OperationResult<bool>(true); } return OperationResult<bool>.FromError("Устройство не найдено"); }
public static bool RemoveAllUsers(GKDevice device, int usersCount, GKProgressCallback progressCallback, Guid clientUID) { var removeAllUsersInternalResult = RemoveAllUsersInternal(device, usersCount, progressCallback); if (removeAllUsersInternalResult.HasError) return false; var cardsCount = removeAllUsersInternalResult.Result; if (cardsCount == 0) return false; using (var skdDatabaseService = new RubezhDAL.DataClasses.DbService()) { GKProcessorManager.DoProgress("Удаление пользователей прибора из БД", progressCallback, clientUID); skdDatabaseService.GKCardTranslator.RemoveAll(device.GetGKIpAddress(), cardsCount); } return true; }
public static OperationResult<bool> GKWriteConfiguration(GKDevice device, string userName, GKProgressCallback progressCallback, Guid clientUID) { AddGKMessage(JournalEventNameType.Запись_конфигурации_в_прибор, JournalEventDescriptionType.NULL, "", device, userName); Stop(); GKSyncronyseTime(device, userName); var gkDescriptorsWriter = new GkDescriptorsWriter(); gkDescriptorsWriter.WriteConfig(device, progressCallback, clientUID); Start(); if (gkDescriptorsWriter.Errors.Count > 0) { var errors = new List<string>(); foreach (var error in gkDescriptorsWriter.Errors) { errors.Add(error); } return OperationResult<bool>.FromError(errors, false); } return new OperationResult<bool>(true); }
public OperationResult<bool> RewritePmfUsers(Guid clientUID, Guid uid, List<GKUser> users) { var progressCallback = new GKProgressCallback(); ServerTaskRunner.Add(progressCallback, "Чтение пользователей прибора", new Action(() => { try { var result = GKSKDHelper.RewritePmfUsers(clientUID, uid, users, progressCallback); RubezhService.NotifyOperationResult_RewriteUsers(result, clientUID); } catch (Exception e) { NotifyOperationResult_RewriteUsers(OperationResult<bool>.FromError(e.Message), clientUID); } } )); return new OperationResult<bool>(true); }
public static void Add(GKProgressCallback progressCallback, string name, Action action) { var serverTask = new ServerTask() { Action = action, ProgressCallback = progressCallback, Name = name }; ServerTasks.Add(serverTask); Notifier.AddServerTask(serverTask); }
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); } }
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; } } }
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; } }
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; }
bool FindDevicesOnKau(GKDevice kauDevice, GKProgressCallback progressCallback, Guid clientUID) { var shleifNos = new List<int>(); shleifNos.Add(0); var als12Property = kauDevice.Properties.FirstOrDefault(x => x.Name == "als12"); if (als12Property != null && als12Property.Value == 0) shleifNos.Add(1); shleifNos.Add(2); var als34Property = kauDevice.Properties.FirstOrDefault(x => x.Name == "als34"); if (als34Property != null && als34Property.Value == 0) shleifNos.Add(3); shleifNos.Add(4); var als56Property = kauDevice.Properties.FirstOrDefault(x => x.Name == "als56"); if (als56Property != null && als56Property.Value == 0) shleifNos.Add(5); shleifNos.Add(6); var als78Property = kauDevice.Properties.FirstOrDefault(x => x.Name == "als78"); if (als78Property != null && als78Property.Value == 0) shleifNos.Add(7); foreach (var shleifNo in shleifNos) { if (!FindDevicesOnShleif(kauDevice, shleifNo, progressCallback, clientUID)) return false; } return true; }
void OnGKProgressCallbackEvent(GKProgressCallback gkProgressCallback) { OnGKProgressCallbackEvent(gkProgressCallback, null); }
static void OnGKProgressCallbackEvent(GKProgressCallback gkProgressCallback, Guid? clientUID) { RubezhService.Service.RubezhService.NotifyGKProgress(gkProgressCallback, clientUID); }
public static OperationResult<List<GKUser>> GetAllUsersTest(GKDevice device, GKProgressCallback progressCallback) { progressCallback = GKProcessorManager.StartProgress("Чтение пользователей прибора " + device.PresentationName, "", 100, true, GKProgressClientType.Administrator); var users = new List<GKUser>(); for (ushort i = 1; i <= 100; i++) { Thread.Sleep(100); var user = new GKUser { GkNo = i, UserType = GKCardType.Administrator, IsActive = true, Fio = "Пользователь " + i, Password = i }; users.Add(user); if (progressCallback.IsCanceled) { return OperationResult<List<GKUser>>.FromError("Операция отменена", users); } GKProcessorManager.DoProgress("Пользователь " + i, progressCallback); } GKProcessorManager.StopProgress(progressCallback); return new OperationResult<List<GKUser>>(users); }
public static OperationResult<string> GKReadConfigurationFromGKFile(GKDevice device, string userName, GKProgressCallback progressCallback, Guid clientUID) { AddGKMessage(JournalEventNameType.Чтение_конфигурации_из_прибора, JournalEventDescriptionType.NULL, "", device, userName); SuspendMonitoring(device); var gkFileReaderWriter = new GKFileReaderWriter(); var filePath = gkFileReaderWriter.ReadConfigFileFromGK(device, progressCallback, clientUID); ResumeMonitoring(device); return filePath; }
public static OperationResult<List<GKUser>> GetAllUsers(GKDevice device, GKProgressCallback progressCallback, Guid clientUID) { progressCallback = GKProcessorManager.StartProgress("Чтение пользователей прибора " + device.PresentationName, "", 65535, true, GKProgressClientType.Administrator, clientUID); var users = new List<GKUser>(); for (int i = 1; i <= 65535; i++) { byte j = 0; bool hasResponse = true; var bytePacks = new List<List<byte>>(); while (true) { var bytes = new List<byte>(); bytes.Add(j); bytes.AddRange(BytesHelper.ShortToBytes((ushort)(i))); var sendResult = SendManager.Send(device, (ushort)(bytes.Count), 24, 0, bytes); if (sendResult.HasError && device.DriverType != GKDriverType.GKMirror) { return OperationResult<List<GKUser>>.FromError("Во время выполнения операции возникла ошибка", users); } if (sendResult.Bytes.Count == 0) { if (j == 0) hasResponse = false; break; } bytePacks.Add(sendResult.Bytes); j++; } if (!hasResponse) break; int packIndex = -1; GKUser user = null; foreach (var pack in bytePacks) { packIndex++; if (packIndex == 0) { var gkNo = BytesHelper.SubstructShort(pack, 1); user = new GKUser { GkNo = gkNo, UserType = (GKCardType)pack[3], IsActive = pack[4] == 0, Fio = BytesHelper.BytesToStringDescription(pack, 5), Password = (uint)BytesHelper.SubstructInt(pack, 37), GkLevel = pack[41], GkLevelSchedule = pack[42] }; var totalSeconds = BytesHelper.SubstructInt(pack, 45); user.ExpirationDate = new DateTime(2000, 1, 1); user.ExpirationDate = user.ExpirationDate.AddSeconds(totalSeconds); for (int l = 0; l < 68; l++) { var deviceNo = BytesHelper.SubstructShort(pack, 49 + l * 2); if (deviceNo == 0) break; var scheduleNo = pack[185 + l]; user.Descriptors.Add(new GKUserDescriptor { DescriptorNo = deviceNo, ScheduleNo = scheduleNo }); } users.Add(user); } else { for (int l = 0; l < 84; l++) { var deviceNo = BytesHelper.SubstructShort(pack, 1 + l * 2); if (deviceNo == 0) break; var scheduleNo = pack[169 + l]; user.Descriptors.Add(new GKUserDescriptor { DescriptorNo = deviceNo, ScheduleNo = scheduleNo }); } } } if (progressCallback.IsCanceled) { return OperationResult<List<GKUser>>.FromError("Операция отменена", users); } GKProcessorManager.DoProgress("Пользователь " + i, progressCallback, clientUID); } GKProcessorManager.StopProgress(progressCallback, clientUID); return new OperationResult<List<GKUser>>(users); }
public static OperationResult<int> GetUsersCount(GKDevice device, GKProgressCallback progressCallback = null) { if (progressCallback != null) progressCallback = GKProcessorManager.StartProgress("Подсчёт числа пользователей на приборе", "", 16, true, GKProgressClientType.Administrator); int minNo = 0; int maxNo = 65535; int currentNo = 65535 / 2; int delta = currentNo / 2; while (maxNo - minNo > 1) { var bytes = new List<byte>(); bytes.Add(0); bytes.AddRange(BytesHelper.ShortToBytes((ushort)(currentNo))); var sendResult = SendManager.Send(device, (ushort)(bytes.Count), 24, 0, bytes); if (sendResult.HasError || sendResult.Bytes.Count == 0) { maxNo = currentNo; currentNo = currentNo - delta; } else { minNo = currentNo; currentNo = currentNo + delta; } delta = delta / 2; if (delta == 0) delta = 1; if (progressCallback != null) { GKProcessorManager.DoProgress("", progressCallback); if (progressCallback.IsCanceled) return OperationResult<int>.FromError("Операция отменена"); } } if (progressCallback != null) GKProcessorManager.StopProgress(progressCallback); return new OperationResult<int>(minNo); }