/// <summary> /// Initializes the class. /// </summary> static TrendsController() { string path = AppDomain.CurrentDomain.BaseDirectory; string LogDir = path + "log" + Path.DirectorySeparatorChar; Log = new Log(Log.Formats.Simple) { Encoding = Encoding.UTF8 }; Log.FileName = LogDir + LogFileName; AppSettings appSettings = new AppSettings(); Log = new Log(Log.Formats.Simple) { Encoding = Encoding.UTF8 }; Log.FileName = LogDir + LogFileName; if (!appSettings.Load(out string errMsg)) { Log.WriteAction(errMsg, Log.ActTypes.Exception); } else { CommSettings settings = new CommSettings(appSettings.ServerHost, appSettings.ServerPort, appSettings.ServerUser, appSettings.ServerPwd, appSettings.ServerTimeout); serverComm = new ServerComm(settings, Log); dataCache = new DataCache(serverComm, Log); dataAccess = new DataAccess(dataCache, Log); } }
/// <summary> /// Конструктор /// </summary> public ServerCommEx(Settings.CommonParams commonParams, Log log) : base() { commSettings = new CommSettings(commonParams.ServerHost, commonParams.ServerPort, commonParams.ServerUser, commonParams.ServerPwd, commonParams.ServerTimeout); this.log = log; }
/// <summary> /// Конструктор /// </summary> public FrmMain() { InitializeComponent(); exeDir = ""; configDir = ""; webAppDir = ""; commSettings = new CommSettings(); webSettings = new WebSettings(); viewSettings = new ViewSettings(); regKey = ""; loadedCommSettings = null; loadedWebSettings = null; loadedViewSettings = null; loadedRegKey = ""; commSettingsChanged = false; webSettingsChanged = false; viewSettingsChanged = false; regKeyChanged = false; showing = false; selViewSet = null; selViewInfo = null; }
/// <summary> /// Конструктор /// </summary> public WebSettings() { CommSettings = new CommSettings(); ScriptPaths = new ScriptPaths(); PluginFileNames = new List <string>(); SetToDefault(); }
private void btnCancel_Click(object sender, EventArgs e) { commSettings = loadedCommSettings.Clone(); viewSettings = loadedViewSettings.Clone(); regKey = loadedRegKey; SettingsToControls(); SetSettingsUnchanged(); }
/// <summary> /// Конструктор /// </summary> public WebSettings() { CommSettings = new CommSettings(); ScriptPaths = new ScriptPaths(); PluginFileNames = new List <string>(); CustomOptions = new SortedList <string, OptionList>(); SetToDefault(); }
/// <summary> /// Call UserControl CommSettings /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Img_CommSettings_MouseDown(object sender, MouseButtonEventArgs e) { cv_ContentUC.Children.Clear(); commSetUC = new CommSettings(); Canvas.SetTop(commSetUC, 98); Canvas.SetLeft(commSetUC, (cv_ContentUC.ActualWidth - commSetUC.Width) / 2); core.UserControlOperations.ContentUserControl(cv_ContentUC, commSetUC); }
/// <summary> /// Обновить настройки соединения с сервером /// </summary> private bool RefreshCommSettings() { bool changed; if (commSettingsUpdater.Update(out changed) && changed) { commSettings = (CommSettings)commSettingsUpdater.Settings; } return(changed); }
/// <summary> /// Gets the object that communicates with the Server service. /// </summary> public ServerComm GetServerComm(Settings settings) { if (AgentClient == null || settings == null) { return(null); } CommSettings commSettings = AgentClient.CreateCommSettings(); commSettings.ServerPort = settings.TcpPort; return(new ServerComm(commSettings, new LogStub())); }
/// <summary> /// Displays server connection settings. /// </summary> private void DisplayCommSettings() { if (serverComm != null) { CommSettings commSettings = serverComm.CommSettings; txtServerHost.Text = commSettings.ServerHost; txtServerPort.Text = commSettings.ServerPort.ToString(); txtServerTimeout.Text = commSettings.ServerTimeout.ToString(); txtServerUser.Text = commSettings.ServerUser; txtServerPwd.Text = commSettings.ServerPwd; } }
/// <summary> /// Initializes the object to communicate with Server. /// </summary> private void InitServerComm() { if (environment.AgentClient == null) { gbGenerator.Enabled = false; pnlProfileWarn.Visible = true; } else { CommSettings commSettings = environment.AgentClient.CreateCommSettings(); commSettings.ServerPort = settings.TcpPort; serverComm = new ServerComm(commSettings, new LogStub()); } }
public bool OpenComm(String strCommDevice, byte byAutodetect, uint dwBaudRate, byte byProtocol) { CommSettings tCommSet = new CommSettings(); tCommSet.baudrate = dwBaudRate; tCommSet.protocol = (sbyte)byProtocol; sbyte b_retv = m_clsRFReader.OpenComm(strCommDevice, byAutodetect, tCommSet); if (b_retv.Equals(1)) { return(true); } return(false); }
/// <summary> /// Обновить настройки веб-приложения /// </summary> private void RefreshWebSettings(out bool webSettingsChanged, out bool commSettingsChanged) { CommSettings oldCommSettings = WebSettings.CommSettings; if (webSettingsUpdater.Update(out webSettingsChanged) && webSettingsChanged) { WebSettings = (WebSettings)webSettingsUpdater.Settings; commSettingsChanged = !oldCommSettings.Equals(WebSettings.CommSettings); } else { commSettingsChanged = false; } }
/// <summary> /// Отобразить форму настроек соединения /// </summary> public static DialogResult Show(CommSettings commSettings) { if (commSettings == null) { throw new ArgumentNullException("commSettings"); } FrmCommSettings frmCommSettings = new FrmCommSettings(); frmCommSettings.commSettings = commSettings; frmCommSettings.txtServerHost.Text = commSettings.ServerHost; frmCommSettings.numServerPort.SetValue(commSettings.ServerPort); frmCommSettings.numServerTimeout.SetValue(commSettings.ServerTimeout); frmCommSettings.txtServerUser.Text = commSettings.ServerUser; frmCommSettings.txtServerPwd.Text = commSettings.ServerPwd; return(frmCommSettings.ShowDialog()); }
/// <summary> /// Установить значения настроек по умолчанию /// </summary> protected void SetToDefault() { Culture = ""; DataRefrRate = 1000; ArcRefrRate = 10000; DispEventCnt = 100; ChartGap = 90; StartPage = ""; CmdEnabled = true; CmdPassword = true; RemEnabled = false; ViewsFromBase = true; ShareStats = true; CommSettings.SetToDefault(); ScriptPaths.SetToDefault(); PluginFileNames.Clear(); }
public RSServers(XDocument xdoc) { rssrvs = new List <RSServer> (); IEnumerable <XElement> cnfs = xdoc.XPathSelectElements("//RSServer"); foreach (XElement cnf in cnfs) { CommSettings cs = new CommSettings() { ServerHost = cnf.Attribute("ServerHost").Value, ServerPort = int.Parse(cnf.Attribute("ServerPort").Value), ServerTimeout = 200, ServerUser = cnf.Attribute("ServerUser").Value, ServerPwd = cnf.Attribute("ServerPwd").Value }; RSServer rssrv = new RSServer(cs, int.Parse(cnf.Attribute("Id").Value)); rssrvs.Add(rssrv); } }
/// <summary> /// Конструктор, ограничивающий создание объекта из других классов /// </summary> private AppData() { appDataLock = new object(); inited = false; commSettings = new CommSettings(); viewStampCntr = 0; WebSettings = new WebSettings(); ViewSettings = new ViewSettings(); PluginSpecs = new List <PluginSpec>(); ViewSpecs = new Dictionary <string, ViewSpec>(); AppDirs = new AppDirs(); Log = new Log(Log.Formats.Full); Storage = new Storage(AppDirs.StorageDir); RememberMe = new RememberMe(Storage, Log); UserMonitor = new UserMonitor(Log); InitUpdaters(); CreateDataObjects(); }
/// <summary> /// Загрузить настройки из файлов /// </summary> private void LoadSettings() { StringBuilder sbErr = new StringBuilder(); string errMsg; SetSettingsUnchanged(); // загрузка настроек соединения if (!commSettings.LoadFromFile(configDir + CommSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } // загрузка настроек отображения if (!webSettings.LoadFromFile(configDir + WebSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } // загрузка настроек представлений if (!viewSettings.LoadFromFile(configDir + ViewSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } // отображение настроек SettingsToControls(); if (sbErr.Length > 0) { ScadaUiUtils.ShowError(sbErr.ToString().TrimEnd()); } loadedCommSettings = commSettings.Clone(); loadedWebSettings = webSettings.Clone(); loadedViewSettings = viewSettings.Clone(); loadedRegKey = regKey; }
/// <summary> /// Сохранить настройки в файлах /// </summary> private void SaveSettings() { StringBuilder sbErr = new StringBuilder(); string errMsg; // сохранение настроек доступа к данным if (commSettingsChanged && !commSettings.SaveToFile(configDir + CommSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } // сохранение настроек отображения if (webSettingsChanged && !webSettings.SaveToFile(configDir + WebSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } // сохранение настроек представлений if (viewSettingsChanged && !viewSettings.SaveToFile(configDir + ViewSettings.DefFileName, out errMsg)) { sbErr.AppendLine(errMsg); } if (sbErr.Length > 0) { ScadaUiUtils.ShowError(sbErr.ToString().TrimEnd()); } else { SetSettingsUnchanged(); loadedCommSettings = commSettings.Clone(); loadedWebSettings = webSettings.Clone(); loadedViewSettings = viewSettings.Clone(); loadedRegKey = regKey; } }
public bool OpenComm(String strCommDevice, byte byAutodetect, uint dwBaudRate, byte byProtocol) { CommSettings tCommSet = new CommSettings(); tCommSet.baudrate = dwBaudRate; tCommSet.protocol = (sbyte)byProtocol; sbyte b_retv = m_clsRFReader.OpenComm(strCommDevice, byAutodetect, tCommSet); if (b_retv.Equals(1)) return true ; return false; }
/// <summary> /// Конструктор /// </summary> public FrmCommSettings() { InitializeComponent(); commSettings = null; }
public override void OnAddedToCommLine() { List <TagGroup> tagGroups = new List <TagGroup>(); TagGroup tagGroup = new TagGroup("GroupMQTT"); TagGroup tagGroupJS = new TagGroup("GoupJS"); XmlDocument xmlDoc = new XmlDocument(); string filename = ReqParams.CmdLine.Trim(); xmlDoc.Load(AppDirs.ConfigDir + filename); XmlNode MQTTSubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttSubTopics"); XmlNode MQTTPubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttPubTopics"); XmlNode MQTTPubCmds = xmlDoc.DocumentElement.SelectSingleNode("MqttPubCmds"); XmlNode MQTTSubCmds = xmlDoc.DocumentElement.SelectSingleNode("MqttSubCmds"); XmlNode MQTTSubJSs = xmlDoc.DocumentElement.SelectSingleNode("MqttSubJSs"); XmlNode RapSrvCnf = xmlDoc.DocumentElement.SelectSingleNode("RapSrvCnf"); MQTTSettings = xmlDoc.DocumentElement.SelectSingleNode("MqttParams"); CommSettings cs = new CommSettings() { ServerHost = RapSrvCnf.Attributes.GetNamedItem("ServerHost").Value, ServerPort = Convert.ToInt32(RapSrvCnf.Attributes.GetNamedItem("ServerPort").Value), ServerUser = RapSrvCnf.Attributes.GetNamedItem("ServerUser").Value, ServerPwd = RapSrvCnf.Attributes.GetNamedItem("ServerPwd").Value }; RSrv = new RapSrvEx(cs); RSrv.Conn(); MQTTPTs = new List <MQTTPubTopic>(); MQTTCmds = new List <MQTTPubCmd>(); foreach (XmlElement MqttPTCnf in MQTTPubTopics) { MQTTPubTopic MqttPT = new MQTTPubTopic() { NumCnl = Convert.ToInt32(MqttPTCnf.GetAttribute("NumCnl")), QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")), TopicName = MqttPTCnf.GetAttribute("TopicName"), PubBehavior = MqttPTCnf.GetAttribute("PubBehavior"), NumberDecimalSeparator = MqttPTCnf.GetAttribute("NDS"), Value = 0 }; MQTTPTs.Add(MqttPT); } foreach (XmlElement MqttPTCnf in MQTTPubCmds) { MQTTPubCmd MqttPTCmd = new MQTTPubCmd() { NumCmd = MqttPTCnf.GetAttrAsInt("NumCmd"), QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")), Retain = false, TopicName = MqttPTCnf.GetAttribute("TopicName") }; MQTTCmds.Add(MqttPTCmd); } sp = new SubscribePacket(); int i = 0; int spCnt = MQTTSubTopics.ChildNodes.Count; spCnt += MQTTSubCmds.ChildNodes.Count; spCnt += MQTTSubJSs.ChildNodes.Count; sp.Topics = new string[spCnt]; sp.QosLevels = new MqttQos[spCnt]; foreach (XmlElement elemGroupElem in MQTTSubTopics.ChildNodes) { sp.Topics[i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels[i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); KPTag KPt = new KPTag() { Signal = i + 1, Name = sp.Topics[i], CnlNum = Convert.ToInt32(elemGroupElem.GetAttribute("NumCnl")) }; tagGroup.KPTags.Add(KPt); i++; } tagGroups.Add(tagGroup); InitKPTags(tagGroups); SubCmds = new List <MQTTSubCmd>(); foreach (XmlElement elemGroupElem in MQTTSubCmds.ChildNodes) { sp.Topics[i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels[i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); MQTTSubCmd cmd = new MQTTSubCmd() { TopicName = sp.Topics[i], CmdNum = elemGroupElem.GetAttrAsInt("NumCmd", 0), CmdType = elemGroupElem.GetAttribute("CmdType"), KPNum = elemGroupElem.GetAttrAsInt("KPNum", 0), IDUser = elemGroupElem.GetAttrAsInt("IDUser", 0), NumCnlCtrl = elemGroupElem.GetAttrAsInt("NumCnlCtrl", 0) }; SubCmds.Add(cmd); i++; } SubJSs = new List <MQTTSubJS>(); foreach (XmlElement elemGroupElem in MQTTSubJSs.ChildNodes) { sp.Topics[i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels[i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); MQTTSubJS msjs = new MQTTSubJS() { TopicName = sp.Topics[i], CnlCnt = elemGroupElem.GetAttrAsInt("CnlCnt", 1), JSHandlerPath = elemGroupElem.GetAttrAsString("JSHandlerPath", "") }; if (msjs.LoadJSHandler()) { SubJSs.Add(msjs); i++; } } Connect(MQTTSettings); }
public RapSrvEx(CommSettings cs) { rsrv = this; rsrv.commSettings = cs; }
public override void OnAddedToCommLine() { List <TagGroup> tagGroups = new List <TagGroup> (); TagGroup tagGroup = new TagGroup("GroupMQTT"); XmlDocument xmlDoc = new XmlDocument(); string filename = ReqParams.CmdLine.Trim(); xmlDoc.Load(AppDirs.ConfigDir + filename); XmlNode MQTTSubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttSubTopics"); XmlNode MQTTPubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttPubTopics"); XmlNode RapSrvCnf = xmlDoc.DocumentElement.SelectSingleNode("RapSrvCnf"); XmlNode MQTTSettings = xmlDoc.DocumentElement.SelectSingleNode("MqttParams"); CommSettings cs = new CommSettings() { ServerHost = RapSrvCnf.Attributes.GetNamedItem("ServerHost").Value, ServerPort = Convert.ToInt32(RapSrvCnf.Attributes.GetNamedItem("ServerPort").Value), ServerUser = RapSrvCnf.Attributes.GetNamedItem("ServerUser").Value, ServerPwd = RapSrvCnf.Attributes.GetNamedItem("ServerPwd").Value }; RSrv = new RapSrvEx(cs); RSrv.Conn(); MQTTPTs = new List <MQTTPubTopic> (); foreach (XmlElement MqttPTCnf in MQTTPubTopics) { MQTTPubTopic MqttPT = new MQTTPubTopic() { NumCnl = Convert.ToInt32(MqttPTCnf.GetAttribute("NumCnl")), QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")), TopicName = MqttPTCnf.GetAttribute("TopicName"), Value = 0 }; MQTTPTs.Add(MqttPT); } sp = new SubscribePacket(); int i = 0; sp.Topics = new string[MQTTSubTopics.ChildNodes.Count]; sp.QosLevels = new MqttQos[MQTTSubTopics.ChildNodes.Count]; foreach (XmlElement elemGroupElem in MQTTSubTopics.ChildNodes) { sp.Topics [i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); KPTag KPt = new KPTag() { Signal = i + 1, Name = sp.Topics [i], CnlNum = Convert.ToInt32(elemGroupElem.GetAttribute("NumCnl")) }; tagGroup.KPTags.Add(KPt); i++; } tagGroups.Add(tagGroup); InitKPTags(tagGroups); connArgs = new MqttConnectionArgs(); connArgs.ClientId = MQTTSettings.Attributes.GetNamedItem("ClientID").Value; connArgs.Hostname = MQTTSettings.Attributes.GetNamedItem("Hostname").Value; connArgs.Port = Convert.ToInt32(MQTTSettings.Attributes.GetNamedItem("Port").Value); connArgs.Username = MQTTSettings.Attributes.GetNamedItem("UserName").Value; connArgs.Password = MQTTSettings.Attributes.GetNamedItem("Password").Value; this.Persistence = new InMemoryPersistence(); Transport = new TcpTransport(connArgs.Hostname, connArgs.Port); Transport.Version = connArgs.Version; Transport.SetTimeouts(connArgs.ReadTimeout, connArgs.WriteTimeout); Send(MakeConnectMessage(connArgs)); ReceiveConnack(); ResumeOutgoingFlows(); Subscribe(sp); }
/// <summary> /// Получить параметры настроек из элементов управления /// </summary> private bool ControlsToSettings(WebSettings webSettings, out string errMsg) { // проверка текстовых полей и установка числовых настроек CommSettings commSettings = webSettings.CommSettings; List <string> errFields = new List <string>(); int val; if (ValidateIntField(pnlServerPort, lblServerPort, txtServerPort, errFields, out val)) { commSettings.ServerPort = val; } if (ValidateIntField(pnlServerTimeout, lblServerTimeout, txtServerTimeout, errFields, out val)) { commSettings.ServerTimeout = val; } if (ValidateIntField(pnlDataRefrRate, lblDataRefrRate, txtDataRefrRate, errFields, out val)) { webSettings.DataRefrRate = val; } if (ValidateIntField(pnlArcRefrRate, lblArcRefrRate, txtArcRefrRate, errFields, out val)) { webSettings.ArcRefrRate = val; } if (ValidateIntField(pnlDispEventCnt, lblDispEventCnt, txtDispEventCnt, errFields, out val)) { webSettings.DispEventCnt = val; } if (ValidateIntField(pnlChartGap, lblChartGap, txtChartGap, errFields, out val)) { webSettings.ChartGap = val; } if (errFields.Count > 0) { errMsg = PlgPhrases.IncorrectFields + "\n" + string.Join(",\n", errFields.ToArray()); return(false); } else { // установка настроек, не требующих проверки commSettings.ServerHost = txtServerHost.Text; commSettings.ServerUser = txtServerUser.Text; if (txtServerPwd.Text != "") { commSettings.ServerPwd = txtServerPwd.Text; } webSettings.Culture = txtCulture.Text; webSettings.StartPage = txtStartPage.Text; webSettings.CmdEnabled = chkCmdEnabled.Checked; webSettings.CmdPassword = chkCmdPassword.Checked; webSettings.RemEnabled = chkRemEnabled.Checked; webSettings.ViewsFromBase = chkViewsFromBase.Checked; webSettings.ShareStats = chkShareStats.Checked; webSettings.ScriptPaths.ChartScriptPath = ddlChartScript.SelectedValue; webSettings.ScriptPaths.CmdScriptPath = ddlCmdScript.SelectedValue; webSettings.ScriptPaths.EventAckScriptPath = ddlEventAckScript.SelectedValue; errMsg = ""; return(true); } }
/// <summary> /// Отобразить настройки /// </summary> private void SettingsToControls(WebSettings webSettings) { CommSettings commSettings = webSettings.CommSettings; txtServerHost.Text = commSettings.ServerHost; txtServerPort.Text = commSettings.ServerPort.ToString(); txtServerTimeout.Text = commSettings.ServerTimeout.ToString(); txtServerUser.Text = commSettings.ServerUser; txtServerPwd.Text = ""; txtCulture.Text = webSettings.Culture; txtDataRefrRate.Text = webSettings.DataRefrRate.ToString(); txtArcRefrRate.Text = webSettings.ArcRefrRate.ToString(); txtDispEventCnt.Text = webSettings.DispEventCnt.ToString(); txtChartGap.Text = webSettings.ChartGap.ToString(); txtStartPage.Text = webSettings.StartPage; chkCmdEnabled.Checked = webSettings.CmdEnabled; chkCmdPassword.Checked = webSettings.CmdPassword; chkRemEnabled.Checked = webSettings.RemEnabled; chkViewsFromBase.Checked = webSettings.ViewsFromBase; chkShareStats.Checked = webSettings.ShareStats; // заполнение списков плагинов ddlChartScript.Items.Clear(); ddlCmdScript.Items.Clear(); ddlEventAckScript.Items.Clear(); ddlChartScript.Items.Add(""); ddlCmdScript.Items.Add(""); ddlEventAckScript.Items.Add(""); string curChartScriptPath = webSettings.ScriptPaths.ChartScriptPath; string curCmdScriptPath = webSettings.ScriptPaths.CmdScriptPath; string curEventAckScriptPath = webSettings.ScriptPaths.EventAckScriptPath; int chartScriptInd = 0; int cmdScriptInd = 0; int eventAckScriptInd = 0; foreach (PluginSpec pluginSpec in userData.PluginSpecs) { ScriptPaths scriptPaths = pluginSpec.ScriptPaths; if (scriptPaths != null) { if (!string.IsNullOrEmpty(scriptPaths.ChartScriptPath)) { ddlChartScript.Items.Add(new ListItem(pluginSpec.Name, scriptPaths.ChartScriptPath)); if (string.Equals(curChartScriptPath, scriptPaths.ChartScriptPath, StringComparison.OrdinalIgnoreCase)) { chartScriptInd = ddlChartScript.Items.Count - 1; } } if (!string.IsNullOrEmpty(scriptPaths.CmdScriptPath)) { ddlCmdScript.Items.Add(new ListItem(pluginSpec.Name, scriptPaths.CmdScriptPath)); if (string.Equals(curCmdScriptPath, scriptPaths.CmdScriptPath, StringComparison.OrdinalIgnoreCase)) { cmdScriptInd = ddlCmdScript.Items.Count - 1; } } if (!string.IsNullOrEmpty(scriptPaths.EventAckScriptPath)) { ddlEventAckScript.Items.Add(new ListItem(pluginSpec.Name, scriptPaths.EventAckScriptPath)); if (string.Equals(curEventAckScriptPath, scriptPaths.EventAckScriptPath, StringComparison.OrdinalIgnoreCase)) { eventAckScriptInd = ddlEventAckScript.Items.Count - 1; } } } } // установка выбранных элементов выпадающих списков if (chartScriptInd > 0 || string.IsNullOrEmpty(curChartScriptPath)) { ddlChartScript.SelectedIndex = chartScriptInd; } else { ddlChartScript.Items.Add(new ListItem(PlgPhrases.UnknownPlugin, curChartScriptPath)); ddlChartScript.SelectedIndex = ddlChartScript.Items.Count - 1; } if (cmdScriptInd > 0 || string.IsNullOrEmpty(curCmdScriptPath)) { ddlCmdScript.SelectedIndex = cmdScriptInd; } else { ddlCmdScript.Items.Add(new ListItem(PlgPhrases.UnknownPlugin, curCmdScriptPath)); ddlCmdScript.SelectedIndex = ddlCmdScript.Items.Count - 1; } if (eventAckScriptInd > 0 || string.IsNullOrEmpty(curEventAckScriptPath)) { ddlEventAckScript.SelectedIndex = eventAckScriptInd; } else { ddlEventAckScript.Items.Add(new ListItem(PlgPhrases.UnknownPlugin, curEventAckScriptPath)); ddlEventAckScript.SelectedIndex = ddlEventAckScript.Items.Count - 1; } }
//public RSServer(){} public RSServer(CommSettings cs, int id) { rssrv = this; rssrv.Id = id; rssrv.commSettings = cs; }
/// <summary> /// Сохранить настройки в файле /// </summary> public bool SaveToFile(string fileName, out string errMsg) { try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmlDecl); XmlElement rootElem = xmlDoc.CreateElement("WebSettings"); xmlDoc.AppendChild(rootElem); // настройки соединения XmlElement commSettingsElem = xmlDoc.CreateElement("CommSettings"); rootElem.AppendChild(commSettingsElem); CommSettings.SaveToXml(commSettingsElem); // общие параметры XmlElement commonParamsElem = xmlDoc.CreateElement("CommonParams"); rootElem.AppendChild(commonParamsElem); commonParamsElem.AppendParamElem("Culture", Culture, "Культура веб-приложения", "Web application culture"); commonParamsElem.AppendParamElem("DataRefrRate", DataRefrRate, "Частота обновления текущих данных и событий, мс", "Current data and events refresh rate, ms"); commonParamsElem.AppendParamElem("ArcRefrRate", ArcRefrRate, "Частота обновления архивных данных, мс", "Archive data refresh rate, ms"); commonParamsElem.AppendParamElem("DispEventCnt", DispEventCnt, "Количество отображаемых событий", "Display events count"); commonParamsElem.AppendParamElem("ChartGap", ChartGap, "Расстояние между точками графика для разрыва, с", "Distance between chart points to make a gap, sec"); commonParamsElem.AppendParamElem("StartPage", StartPage, "Начальная страница после входа в систему", "Start page after login"); commonParamsElem.AppendParamElem("CmdEnabled", CmdEnabled, "Разрешить команды ТУ", "Enable commands"); commonParamsElem.AppendParamElem("CmdPassword", CmdPassword, "Требовать пароль при отправке команды", "Require password to send command"); commonParamsElem.AppendParamElem("RemEnabled", RemEnabled, "Разрешить запоминать вход пользователя", "Allow to remember logged on user"); commonParamsElem.AppendParamElem("ViewsFromBase", ViewsFromBase, "Загружать настройки представлений из базы", "Load view settings from the database"); commonParamsElem.AppendParamElem("ShareStats", ShareStats, "Поделиться обезличенной статистикой с разработчиками", "Share depersonalized stats with the developers"); // пути к скриптам XmlElement scriptPathsElem = xmlDoc.CreateElement("ScriptPaths"); rootElem.AppendChild(scriptPathsElem); XmlElement scriptElem = xmlDoc.CreateElement("Script"); scriptElem.SetAttribute("name", "ChartScript"); scriptElem.SetAttribute("path", ScriptPaths.ChartScriptPath); scriptPathsElem.AppendChild(scriptElem); scriptElem = xmlDoc.CreateElement("Script"); scriptElem.SetAttribute("name", "CmdScript"); scriptElem.SetAttribute("path", ScriptPaths.CmdScriptPath); scriptPathsElem.AppendChild(scriptElem); scriptElem = xmlDoc.CreateElement("Script"); scriptElem.SetAttribute("name", "EventAckScript"); scriptElem.SetAttribute("path", ScriptPaths.EventAckScriptPath); scriptPathsElem.AppendChild(scriptElem); // плагины XmlElement pluginsElem = xmlDoc.CreateElement("Plugins"); rootElem.AppendChild(pluginsElem); foreach (string pluginFileName in PluginFileNames) { scriptElem = xmlDoc.CreateElement("Plugin"); scriptElem.SetAttribute("fileName", pluginFileName); pluginsElem.AppendChild(scriptElem); } // custom options XmlElement customOptionsElem = rootElem.AppendElem("CustomOptions"); foreach (KeyValuePair <string, OptionList> pair in CustomOptions) { XmlElement optionGroupElem = customOptionsElem.AppendElem("OptionGroup"); optionGroupElem.SetAttribute("name", pair.Key); pair.Value.SaveToXml(optionGroupElem); } // сохранение в файле string bakName = fileName + ".bak"; File.Copy(fileName, bakName, true); xmlDoc.Save(fileName); errMsg = ""; return(true); } catch (Exception ex) { errMsg = WebPhrases.SaveWebSettingsError + ": " + ex.Message; return(false); } }
/// <summary> /// Загрузить настройки из файла /// </summary> public bool LoadFromFile(string fileName, out string errMsg) { // установка значений по умолчанию SetToDefault(); // загрузка настроек try { if (!File.Exists(fileName)) { throw new FileNotFoundException(string.Format(CommonPhrases.NamedFileNotFound, fileName)); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); XmlElement rootElem = xmlDoc.DocumentElement; // загрузка настроек соединения с сервером if (rootElem.SelectSingleNode("CommSettings") is XmlNode commSettingsNode) { CommSettings.LoadFromXml(commSettingsNode); } // загрузка общих параметров if (rootElem.SelectSingleNode("CommonParams") is XmlNode commonParamsNode) { foreach (XmlElement paramElem in commonParamsNode.SelectNodes("Param")) { string name = paramElem.GetAttribute("name").Trim(); string nameL = name.ToLowerInvariant(); string val = paramElem.GetAttribute("value"); try { if (nameL == "culture") { Culture = val; } else if (nameL == "datarefrrate") { DataRefrRate = Math.Max(MinDataRefrRate, int.Parse(val)); } else if (nameL == "arcrefrrate") { ArcRefrRate = Math.Max(MinDataRefrRate, int.Parse(val)); } else if (nameL == "dispeventcnt") { DispEventCnt = int.Parse(val); } else if (nameL == "chartgap") { ChartGap = int.Parse(val); } else if (nameL == "cmdenabled") { CmdEnabled = bool.Parse(val); } else if (nameL == "cmdpassword") { CmdPassword = bool.Parse(val); } else if (nameL == "remenabled") { RemEnabled = bool.Parse(val); } else if (nameL == "startpage") { StartPage = val; } else if (nameL == "viewsfrombase") { ViewsFromBase = bool.Parse(val); } else if (nameL == "sharestats") { ShareStats = bool.Parse(val); } } catch { throw new ScadaException(string.Format(CommonPhrases.IncorrectXmlParamVal, name)); } } } // загрузка путей к скриптам if (rootElem.SelectSingleNode("ScriptPaths") is XmlNode scriptPathsNode) { foreach (XmlElement scriptElem in scriptPathsNode.SelectNodes("Script")) { string name = scriptElem.GetAttribute("name").Trim(); string nameL = name.ToLowerInvariant(); string path = scriptElem.GetAttribute("path"); if (nameL == "chartscript") { ScriptPaths.ChartScriptPath = path; } else if (nameL == "cmdscript") { ScriptPaths.CmdScriptPath = path; } else if (nameL == "eventackscript") { ScriptPaths.EventAckScriptPath = path; } } } // загрузка имён файлов модулей if (rootElem.SelectSingleNode("Plugins") is XmlNode pluginsNode) { foreach (XmlElement moduleElem in pluginsNode.SelectNodes("Plugin")) { PluginFileNames.Add(moduleElem.GetAttribute("fileName")); } } PluginFileNames.Sort(); // custom options if (rootElem.SelectSingleNode("CustomOptions") is XmlNode customOptionsNode) { foreach (XmlElement optionGroupElem in customOptionsNode.SelectNodes("OptionGroup")) { OptionList optionList = new OptionList(); optionList.LoadFromXml(optionGroupElem); CustomOptions[optionGroupElem.GetAttrAsString("name")] = optionList; } } errMsg = ""; return(true); } catch (Exception ex) { errMsg = WebPhrases.LoadWebSettingsError + ": " + ex.Message; return(false); } }
public override void OnAddedToCommLine() { List <TagGroup> tagGroups = new List <TagGroup> (); TagGroup tagGroup = new TagGroup("GroupMQTT"); TagGroup tagGroupJS = new TagGroup("GoupJS"); XmlDocument xmlDoc = new XmlDocument(); string filename = ReqParams.CmdLine.Trim(); xmlDoc.Load(AppDirs.ConfigDir + filename); XmlNode MQTTSubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttSubTopics"); XmlNode MQTTPubTopics = xmlDoc.DocumentElement.SelectSingleNode("MqttPubTopics"); XmlNode MQTTPubCmds = xmlDoc.DocumentElement.SelectSingleNode("MqttPubCmds"); XmlNode MQTTSubCmds = xmlDoc.DocumentElement.SelectSingleNode("MqttSubCmds"); XmlNode MQTTSubJSs = xmlDoc.DocumentElement.SelectSingleNode("MqttSubJSs"); XmlNode RapSrvCnf = xmlDoc.DocumentElement.SelectSingleNode("RapSrvCnf"); XmlNode MQTTSettings = xmlDoc.DocumentElement.SelectSingleNode("MqttParams"); CommSettings cs = new CommSettings() { ServerHost = RapSrvCnf.Attributes.GetNamedItem("ServerHost").Value, ServerPort = Convert.ToInt32(RapSrvCnf.Attributes.GetNamedItem("ServerPort").Value), ServerUser = RapSrvCnf.Attributes.GetNamedItem("ServerUser").Value, ServerPwd = RapSrvCnf.Attributes.GetNamedItem("ServerPwd").Value }; RSrv = new RapSrvEx(cs); RSrv.Conn(); MQTTPTs = new List <MQTTPubTopic> (); MQTTCmds = new List <MQTTPubCmd> (); foreach (XmlElement MqttPTCnf in MQTTPubTopics) { MQTTPubTopic MqttPT = new MQTTPubTopic() { NumCnl = Convert.ToInt32(MqttPTCnf.GetAttribute("NumCnl")), QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")), TopicName = MqttPTCnf.GetAttribute("TopicName"), PubBehavior = MqttPTCnf.GetAttribute("PubBehavior"), NumberDecimalSeparator = MqttPTCnf.GetAttribute("NDS"), Value = 0 }; MQTTPTs.Add(MqttPT); } foreach (XmlElement MqttPTCnf in MQTTPubCmds) { MQTTPubCmd MqttPTCmd = new MQTTPubCmd() { NumCmd = MqttPTCnf.GetAttrAsInt("NumCmd"), QosLevels = (MqttQos)Convert.ToByte(MqttPTCnf.GetAttribute("QosLevel")), Retain = false, TopicName = MqttPTCnf.GetAttribute("TopicName") }; MQTTCmds.Add(MqttPTCmd); } sp = new SubscribePacket(); int i = 0; int spCnt = MQTTSubTopics.ChildNodes.Count; spCnt += MQTTSubCmds.ChildNodes.Count; spCnt += MQTTSubJSs.ChildNodes.Count; sp.Topics = new string[spCnt]; sp.QosLevels = new MqttQos[spCnt]; foreach (XmlElement elemGroupElem in MQTTSubTopics.ChildNodes) { sp.Topics [i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); KPTag KPt = new KPTag() { Signal = i + 1, Name = sp.Topics [i], CnlNum = Convert.ToInt32(elemGroupElem.GetAttribute("NumCnl")) }; tagGroup.KPTags.Add(KPt); i++; } tagGroups.Add(tagGroup); InitKPTags(tagGroups); SubCmds = new List <MQTTSubCmd> (); foreach (XmlElement elemGroupElem in MQTTSubCmds.ChildNodes) { sp.Topics [i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels [i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); MQTTSubCmd cmd = new MQTTSubCmd() { TopicName = sp.Topics[i], CmdNum = elemGroupElem.GetAttrAsInt("NumCmd", 0), CmdType = elemGroupElem.GetAttribute("CmdType"), KPNum = elemGroupElem.GetAttrAsInt("KPNum", 0), IDUser = elemGroupElem.GetAttrAsInt("IDUser", 0), NumCnlCtrl = elemGroupElem.GetAttrAsInt("NumCnlCtrl", 0) }; SubCmds.Add(cmd); i++; } SubJSs = new List <MQTTSubJS>(); foreach (XmlElement elemGroupElem in MQTTSubJSs.ChildNodes) { sp.Topics[i] = elemGroupElem.GetAttribute("TopicName"); sp.QosLevels[i] = (MqttQos)Convert.ToByte(elemGroupElem.GetAttribute("QosLevel")); MQTTSubJS msjs = new MQTTSubJS() { TopicName = sp.Topics[i], CnlCnt = elemGroupElem.GetAttrAsInt("CnlCnt", 1), JSHandlerPath = elemGroupElem.GetAttrAsString("JSHandlerPath", "") }; if (msjs.LoadJSHandler()) { SubJSs.Add(msjs); i++; } } connArgs = new MqttConnectionArgs(); connArgs.ClientId = MQTTSettings.Attributes.GetNamedItem("ClientID").Value; connArgs.Hostname = MQTTSettings.Attributes.GetNamedItem("Hostname").Value; connArgs.Port = Convert.ToInt32(MQTTSettings.Attributes.GetNamedItem("Port").Value); connArgs.Username = MQTTSettings.Attributes.GetNamedItem("UserName").Value; connArgs.Password = MQTTSettings.Attributes.GetNamedItem("Password").Value; connArgs.Keepalive = TimeSpan.FromSeconds(60); connArgs.ReadTimeout = TimeSpan.FromSeconds(10); connArgs.WriteTimeout = TimeSpan.FromSeconds(10); this.Persistence = new InMemoryPersistence(); Transport = new TcpTransport(connArgs.Hostname, connArgs.Port); Transport.Version = connArgs.Version; Transport.SetTimeouts(connArgs.ReadTimeout, connArgs.WriteTimeout); Send(MakeConnectMessage(connArgs)); ReceiveConnack(); ResumeOutgoingFlows(); if (sp.Topics.Length > 0) { Subscribe(sp); } WriteToLog(Localization.UseRussian ? "Инициализация линии связи выполнена успешно." : "Communication line initialized successfully"); }