Exemple #1
0
        private void FormMain_Load(object sender, EventArgs e)
        {
            #region Защита от повторного запуска

            var process = RunningInstance();
            if (process != null)
            {
                Application.Exit(); return;
            }

            #endregion

            Width = 0; Height = 1;

            Data.Session = new MemIniFile("");

            Data.FileToErrorsFullName = Path.ChangeExtension(Application.ExecutablePath, ".err");
            Data.ResetErrorsLog();

            var tasksFileName = Path.ChangeExtension(Application.ExecutablePath, ".tsk");
            Data.Tasks = new MemIniFile(tasksFileName);

            var configFileName = Path.ChangeExtension(Application.ExecutablePath, ".ini");
            Data.Config = new MemIniFile(configFileName);
            var currentPath = Application.StartupPath;

            var configFolder = Path.Combine(currentPath, "MultiFillingConfig");
            if (!Directory.Exists(configFolder))
            {
                try
                {
                    Directory.CreateDirectory(configFolder);
                }
                catch (Exception ex)
                {
                    Data.SendToErrorsLog("Ошибка при создании папки " + configFolder + ": " + ex.FullMessage());
                    Application.Exit();
                    return;
                }
            }
            Data.ConfigFolder = configFolder;

            #region импорт файла типов вагонов

            //var typeFile = Path.Combine(configFolder, "waggontypes.txt");
            //if (File.Exists(typeFile))
            //{
            //    TypesListKeeper.Clear();
            //    var n = 0;
            //    foreach (var vals in File.ReadLines(typeFile).Select(line => line.Split(new[] { '\t' })))
            //    {
            //        if (n > 0 && vals.Length == 5)
            //        {
            //            int diameter, throat, deflevel;
            //            if (!string.IsNullOrWhiteSpace(vals[0]) &&
            //                int.TryParse(vals[1], out diameter) &&
            //                int.TryParse(vals[2], out throat) &&
            //                int.TryParse(vals[3], out deflevel))
            //            {
            //                TypesListKeeper.Add(vals[0], diameter, throat, deflevel);
            //            }
            //        }
            //        n++;
            //    }
            //    typeFile = Path.Combine(configFolder, "wagtypes.xml");
            //    TypesListKeeper.SaveTypesData(typeFile);
            //}

            #endregion

            TypeDataKeeper.LoadTypesData(Path.Combine(configFolder, "wagtypes.xml"));

            #region импорт и экспорт файла вагонов

            //var wagFile = Path.Combine(configFolder, "_waggons.txt");
            //if (File.Exists(wagFile))
            //{
            //    var filename = Path.Combine(configFolder, "waggons.txt");
            //    using (var stream = new FileStream(filename, FileMode.Append))
            //    {
            //        using (var writer = new StreamWriter(stream))
            //        {
            //            var n = 0;
            //            foreach (var vals in File.ReadLines(wagFile).Select(line => line.Split(new[] {'\t'})))
            //            {
            //                if (n > 0 && vals.Length == 5)
            //                {
            //                    var number = vals[0];
            //                    var ntype = vals[1];
            //                    int factlevel;
            //                    if (!string.IsNullOrWhiteSpace(number) &&
            //                        !string.IsNullOrWhiteSpace(ntype) &&
            //                        int.TryParse(vals[2], out factlevel))
            //                    {
            //                        var content = string.Format("{0}\t{1}\t{2}", number, ntype, factlevel);
            //                        writer.WriteLine(content);
            //                        writer.Flush();
            //                    }
            //                }
            //                n++;
            //            }
            //        }
            //    }
            //}

            #endregion

            var logFolder = Path.Combine(currentPath, "MultiFillingLogs");
            if (!Directory.Exists(logFolder))
            {
                try
                {
                    Directory.CreateDirectory(logFolder);
                }
                catch (Exception ex)
                {
                    Data.SendToErrorsLog("Ошибка при создании папки " + logFolder + ": " + ex.FullMessage());
                    Application.Exit();
                    return;
                }
            }
            Data.LogsFolder = logFolder;

            Data.SendToSystemLog(string.Format("Запуск системы на станции {0}", Environment.MachineName));
            var dt = DateTime.Now + new TimeSpan(0, 0, 0, 3);
            while (dt > DateTime.Now)
            {
                Application.DoEvents();
            }

            _fileLogsWatcher = new FileSystemWatcher
            {
                Path = logFolder,
                EnableRaisingEvents = true,
                Filter              = "*.log",
                NotifyFilter        = NotifyFilters.LastWrite,
                SynchronizingObject = this
            };
            _fileLogsWatcher.Changed += fileSystemLogWatcher_Changed;
            _fileLogsWatcher.Created += fileSystemLogWatcher_Changed;


            var historyFolder = Path.Combine(currentPath, "MultiFillingHistory");
            if (!Directory.Exists(historyFolder))
            {
                try
                {
                    Directory.CreateDirectory(historyFolder);
                }
                catch (Exception ex)
                {
                    Data.SendToErrorsLog("Ошибка при создании папки " + historyFolder + ": " + ex.FullMessage());
                    Application.Exit();
                    return;
                }
            }
            Data.HistoryFolder = historyFolder;

            Data.SystemShell       = Data.Config.ReadBool("GeneralFor" + Environment.UserName, "SystemShell", false);
            Data.StartTaskPeriod   = Data.Config.ReadInteger("General", "StartTaskPeriod", 3000);
            Data.StopTaskPeriod    = Data.Config.ReadInteger("General", "StopTaskPeriod", 3000);
            Data.DeleteLogsAfter   = Data.Config.ReadInteger("General", "DeleteLogsAfter", 90);
            Data.DeleteTrendsAfter = Data.Config.ReadInteger("General", "DeleteTrendsAfter", 14);

            Data.ShowReadyAndAlarm   = Data.Config.ReadBool("FillingPageCommon", "ShowReadyAndAlarm", false);
            Data.UseSmartLevel       = Data.Config.ReadBool("FillingPageCommon", "UseSmartLevel", true);
            Data.SmartLevelDifferent = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelDifferent", 3);
            Data.SmartLevelQueueSize = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelQueueSize", 15);

            // Загрузка конфигурации опроса
            try
            {
                LoadFetchConfiguration();
            }
            catch (Exception ex)
            {
                Data.SendToErrorsLog("Ошибка при загрузке конфигурации опроса: " + ex.FullMessage());
            }

            #region Построение рабочих панелей

            var monitors = Screen.AllScreens;

            _panels = new FormPanel[monitors.Length];

            if (!Data.Config.KeyExists("Station", "Monitors"))
            {
                Data.Config.WriteInteger("Station", "Monitors", 1);
                Data.Config.UpdateFile();
            }
            var screens = Data.Config.ReadInteger("Station", "Monitors", 1);

            for (var i = 0; i < monitors.Length; i++)
            {
                _panels[i] = new FormPanel(this, monitors[i].Primary, monitors[i].WorkingArea)
                {
                    Visible      = false,
                    DisplayIndex = i + 1
                };
                _panels[i].Show(this);
                _panels[i].Refresh();
                if (screens > 0 && i + 1 >= screens)
                {
                    break;
                }
            }

            #endregion

            Data.StationNodes[0] = new StationNode {
                Name = "Станция 1", Index = 1
            };
            Data.StationNodes[1] = new StationNode {
                Name = "Станция 2", Index = 2
            };
            Data.StationNodes[2] = new StationNode {
                Name = "Станция 3", Index = 3
            };
            Data.StationNodes[3] = new StationNode {
                Name = "Станция 4", Index = 4
            };

            Data.EnableLocalEventServer = Data.Config.ReadBool("DataEventServers", "EnableLocalEventServer", false);

            // Запуск сервера событий
            if (Data.EnableLocalEventServer)
            {
                _wcfEventService = WcfEventService.EventService;
                try
                {
                    _wcfEventService.Start();
                }
                catch (Exception ex)
                {
                    Data.SendToErrorsLog("Ошибка при запуске локального сервера событий: " + ex.FullMessage());
                }
                // Подключаемся клиентом сами к себе для рассылки событий возможным клиентам
                Data.LocalEventClient = new EventClient.EventClient();
                Data.LocalEventClient.Connect("localhost", 9901, new[] { "Fetching", "Logging", "Trending" },
                                              PropertyUpdate, ShowError, ClientFileReceived, UpdateLocalConnectionStatus);
            }


            Data.SelfIpAddress = Data.Config.ReadString("DataEventServers", "SelfIpAddress", "");
            //var selfIpAddresses = Dns.GetHostAddresses(Dns.GetHostName());

            // Подключаемся клиентом к другим станциям
            for (var i = 1; i <= Data.StationNodes.Length; i++)
            {
                var enable = Data.Config.ReadBool("DataEventServers", "EnableEventServer" + i, false);
                Data.StationNodes[i - 1].Enable = enable;
                var addr = Data.Config.ReadString("DataEventServers", "AddressEventServer" + i, "");
                if (!enable)
                {
                    continue;
                }
                IPAddress address;
                if (IPAddress.TryParse(addr, out address))
                {
                    Data.StationNodes[i - 1].Address = address;
                    if (addr.Equals(Data.SelfIpAddress))
                    {
                        Data.StationNodes[i - 1].ItThisStation = true;
                        Data.StationNodes[i - 1].Descriptor    = "Эта станция";
                    }
                    if (!Data.StationNodes[i - 1].ItThisStation)
                    {
                        var id = Data.ConnectToEventServer(addr, 9901, new[] { "Fetching", "Logging", "Trending" },
                                                           PropertyUpdate, ShowError, ClientFileReceived,
                                                           UpdateConnectionStatus);
                        Data.StationNodes[i - 1].ClientId = id;
                    }
                }
                else
                {
                    Data.SendToErrorsLog(
                        string.Format("Ошибка в IP-адресе для сервера подписки {0} в файле конфигурации", i));
                }
            }

            // ----
            lock (Data.RiserNodes)
            {
                foreach (var riser in Data.RiserNodes.Values)
                {
                    if (string.IsNullOrWhiteSpace(riser.Number))
                    {
                        continue;
                    }
                    var riserName = string.Format("{0}_{1}_{2}_{3}_{4}",
                                                  riser.Channel, riser.Overpass, riser.Way,
                                                  riser.Product, riser.Riser);
                    Data.UpdateRiserProperty(riserName, "Number", riser.Number);
                    Data.UpdateRiserProperty(riserName, "Ntype", riser.Ntype);
                    Data.UpdateRiserProperty(riserName, "FactHeight", riser.FactHeight.ToString("0"));
                    Data.UpdateRiserProperty(riserName, "Setpoint", riser.Setpoint.ToString("0"));
                    Data.UpdateRiserProperty(riserName, "FilledKind", "");
                }
            }
            // Запуск таймера для фонового удаления старых архивов
            _timer.Enabled = true;
        }