private void GetLocalServer() { //获取本地计算机IP,计算机名称 strHostName = System.Net.Dns.GetHostName(); //或者通过局域网内计算机名称 //获取本地计算机上的OPCServerName try { MyServer = new OPCServer(); object serverList = MyServer.GetOPCServers(strHostName); foreach (string server in (Array)serverList) { //cmbServerName.Items.Add(turn); Console.WriteLine("本地OPC服务器:{0}", server); } } catch (Exception err) { Console.WriteLine("枚举本地OPC服务器出错:{0}", err.Message); } }
////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns a array of local opc servers /// </summary> /// <returns></returns> ////////////////////////////////////////////////////////////////////////////////////////////// public static string[] ListOPCServers() { List<string> list = new List<string>(); OPCServer server = new OPCServer(); object result = server.GetOPCServers(null); if (result != null && result is Array) { Array servers = result as Array; foreach (string s in servers) { list.Add(s); } } return list.ToArray(); }
protected override void OnStop() { try { //释放所有组资源 if (null != objGroup) { objGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange); objGroup.AsyncWriteComplete -= new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(AsyncWriteComplete); objGroup = null; objServer.OPCGroups.RemoveAll(); SystemLogs.InsertPLCLog("AndonResult", "释放所有组资源!"); } if (null != objServer) { objServer.Disconnect(); objServer = null; objItems = null; GC.Collect(); SystemLogs.InsertPLCLog("AndonResult", "断开连接OPC释放所有组资源!"); } } catch (Exception ex) { SystemLogs.InsertPLCLog("AndonResult", ex.Message); } }
protected override bool close() { try { if (OpcGrp != null) { OpcGrp = null; } if (Opc != null) { if (Opc.ServerState == 1) { Opc.Disconnect(); } Opc = null; } if (bolOpcStatus) { bolOpcStatus = false; this.ChConnection_Status(bolOpcStatus); } this.dtAddress.Clear(); } catch (Exception ex) //opc 클라이언트가 종료 되면.. 에러 발생.. { throw ex; } return(true); }
/// <summary> /// 连接OPC服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ConnectOPCServerBtn_Click(object sender, RoutedEventArgs e) { try { ConnectedOPCServer = new OPCServer(); ConnectedOPCServer.ServerShutDown += ConnectedOPCServer_ServerShutDown; ConnectedOPCServer.Connect(OPCServerTB.Text, OPCNodeNameTB.Text); ConnectedOPCServer.OPCGroups.DefaultGroupIsActive = true; ConnectedOPCServer.OPCGroups.DefaultGroupDeadband = 0; /// 初始化OPC组 if (InitOPCGroup()) { ConnectOPCServerBtn.IsEnabled = false; StartComponents(); } } catch (Exception ex) { ConnectedOPCServer = null; ConnectOPCServerBtn.IsEnabled = true; LogUtil.Logger.Error(ex.Message, ex); MessageBox.Show(ex.Message); } }
/// <summary> /// 连接服务器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnConIP_Click(object sender, EventArgs e) { //根据输入获取OPC服务器IP地址 strHostIP = txtIP.Text; //通过IP来获取OPC服务器主机名 IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostIP); strHostName = ipHostEntry.HostName.ToString(); try { //实例化OPC服务 myServer = new OPCServer(); //获取OPCServer列表 object serverList = myServer.GetOPCServers(strHostName); //将OPCServer展示到ComboBox foreach (string turn in (Array)serverList) { cmbServer.Items.Add(turn); } cmbServer.SelectedIndex = 0; //开启OPC连接按钮 btnOPC.Enabled = true; } catch (Exception err) { MessageBox.Show("枚举OPC服务出错:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void Init() { MyServer = new OPCServer(); //初始化item数组 MyItem = new OPCItem[4]; MyServer.Connect("KEPware.KEPServerEx.V4", "127.0.0.1");//连接本地服务器:服务器名+主机名或IP if (MyServer.ServerState == (int)OPCServerState.OPCRunning) { Console.WriteLine("已连接到:{0}", MyServer.ServerName); Console.WriteLine("几个组:{0}", MyServer.OPCGroups.Count); } else { //这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档 string errMessage = MyServer.ServerState.ToString(); throw new Exception(errMessage); } MyGroups = MyServer.OPCGroups; MyGroup = MyServer.OPCGroups.Add("GE.GE330.GEPLC"); MyGroup.UpdateRate = 250; MyGroup.IsActive = true; MyGroup.IsSubscribed = true; //MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); MyItems = MyGroup.OPCItems; //添加item MyItem[0] = MyItems.AddItem("GE.GE330.GEPLC.M8001", 0); //bool-buildable MyItem[1] = MyItems.AddItem("GE.GE330.GEPLC.M801", 1); //bool- MyItem[2] = MyItems.AddItem("GE.GE330.GEPLC.M802", 2); //bool- MyItem[3] = MyItems.AddItem("GE.GE330.GEPLC.PLC_PC_S", 3); //string }
public Boolean PutData(Array Values) { IntData.IsOPCConnected = true; OPCServer OPCSvr = new OPCServer(); try { Transacting = true; TransactionFlag = true; IntData.IsOPCConnected = true; opcgrp_server = new OPCServer(); opcgrp_server.Connect(ServerName); opcgrp_group = opcgrp_server.OPCGroups.Add(GroupName); TotalItemNumber = opcgrp_arrayPaths.Length - 1; opcgrp_group.OPCItems.DefaultIsActive = true; opcgrp_group.OPCItems.AddItems(TotalItemNumber, opcgrp_arrayPaths, opcgrp_arrayHandles, out opcgrp_arraySHandles, out opcgrp_arrayErrors); opcgrp_group.SyncWrite(TotalItemNumber, ref opcgrp_arraySHandles, ref Values, out opcgrp_arrayErrors); opcgrp_group.OPCItems.Remove(TotalItemNumber, ref opcgrp_arraySHandles, out opcgrp_arrayErrors); opcgrp_server.Disconnect(); OPCSvr = null; Transacting = false; Thread.Sleep(1000); return(true); } catch (Exception ex) { IntData.IsOPCConnected = false; Console.WriteLine(ex.Message); return(true); } }
static void Main(string[] args) { Console.Out.WriteLine("hello"); var settings = ConfigurationManager.AppSettings; String ser = settings["OPCServerIP"]; String opcName = "OPC.DeltaV.1"; String opcUrl = "192.168.102.11"; opcName = Console.ReadLine(); opcUrl = Console.ReadLine(); OPCServer opcserver = new OPCServer(); try { opcserver.Connect(opcName, opcUrl); if (opcserver.ServerState == (int)OPCServerState.OPCRunning) { Console.Out.WriteLine("opc running"); } } catch (Exception e) { Console.Out.WriteLine(e.Message); } opcserver.Disconnect(); Console.Out.WriteLine("hello"); while (true) { } }
public Form1() { InitializeComponent(); try { SignalRTimer = new Timer(); SignalRTimer.Interval = 1500; SignalRTimer.Tick += SignalRTimer_Tick; SignalRTimer.Enabled = true; OPCconnectTimer = new Timer(); OPCconnectTimer.Interval = 1000; OPCconnectTimer.Tick += OPCconnectTimer_Tick; OPCconnectTimer.Enabled = true; //初始化链接状态定时器 tim = new Timer(); //定义一个1S的定时器; tim.Interval = 1500; tim.Tick += theout; //定时时间到后执行theout事件; tim.Enabled = true;; //是否执行System.Timers.Timer.Elapsed事件; //(1)创建opc server对象 objServer = new OPCServer(); //objChangeItem = new OPCItem[4]; } catch (Exception ex) { SystemLogs.InsertPLCLog("AndonResult", ex.Message); } }
protected override void OnStart(string[] args) { try { SignalRTimer = new Timer(); SignalRTimer.Interval = 1500; SignalRTimer.Elapsed += new ElapsedEventHandler(SignalRTimer_Tick); SignalRTimer.Enabled = true; OPCconnectTimer = new Timer(); OPCconnectTimer.Interval = 1000; OPCconnectTimer.Elapsed += new ElapsedEventHandler(OPCconnectTimer_Tick); OPCconnectTimer.Enabled = true; //初始化链接状态定时器 tim = new Timer(); //定义一个1S的定时器; tim.Interval = 1500; tim.Elapsed += new ElapsedEventHandler(theout); //定时时间到后执行theout事件; tim.Enabled = true;; //是否执行System.Timers.Timer.Elapsed事件; //(1)创建opc server对象 objServer = new OPCServer(); //objChangeItem = new OPCItem[4]; } catch (Exception ex) { SystemLogs.InsertPLCLog("AndonResult", ex.Message); } }
private void GetLocalServer() { //获取本地计算机IP,计算机名称 IPHostEntry IPHost = Dns.Resolve(Environment.MachineName); if (IPHost.AddressList.Length > 0) { strHostIP = IPHost.AddressList[0].ToString(); } else { return; } //通过IP来获取计算机名称,可用在局域网内 IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP); strHostName = ipHostEntry.HostName.ToString(); //获取本地计算机上的OPCServerName try { KepServer = new OPCServer(); object serverList = KepServer.GetOPCServers(strHostName); ArrayList _list = new ArrayList(); foreach (string turn in (Array)serverList) { _list.Add(turn); } } catch (Exception err) { MessageBox.Show("枚举本地OPC服务器出错:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// 初始化OPC服务 /// </summary> public void connectOPC() { KepServer = new OPCServer(); try { if (type == 0) { KepServer.Connect("OPC.SimaticNET", "192.168.48.232"); } else if (type == 1) { KepServer.Connect("OPCServer.WinCC", "192.168.36.135"); } else if (type == 2) { KepServer.Connect("OPCServer.WinCC", "192.168.48.135"); } else if (type == 3) { KepServer.Connect("OPCServer.WinCC", "192.168.36.125"); } else if (type == 4) { KepServer.Connect("OPCServer.WinCC", "192.168.48.125"); } else if (type == 5) { //KepServer.Connect("KEPware.KEPServerEx.V5", "192.168.48.243"); KepServer.Connect("KEPware.KEPServerEx.V6", "192.168.48.163"); } opc_connected = true; KepGroups = KepServer.OPCGroups; KepGroup = KepGroups.Add("myGroup"); KepGroup.IsSubscribed = true; KepGroup.DataChange += Group_DataChange; KepEventGroup = KepGroups.Add("myEventGroup"); KepEventGroup.IsSubscribed = true; foreach (var item in listTag) { if (item.scanrate > 0) { OPCItem myItem = KepGroup.OPCItems.AddItem(item.name, item.id); myItem.ClientHandle = item.id; item.itmHandleServer = myItem.ServerHandle; } else { OPCItem myItem = KepEventGroup.OPCItems.AddItem(item.name, item.id); item.itmHandleServer = myItem.ServerHandle; } } } catch (Exception ex) { throw new Exception("初始化OPC服务时,出现错误:" + type + ex.ToString()); } }
public Server(string name) { _name = name; _opcServer = new OPCServer(); _opcGroups = new List <Group>(); Connect(); }
/// <summary> /// 获取OPC服务器的相关信息 /// </summary> /// <param name="opcServer">OPC服务器对象</param> /// <returns>OPC服务器信息</returns> public OPCServerInfo GetServerInfo(OPCServer opcServer) { OPCServerInfo serverInfo = new OPCServerInfo(); serverInfo.StartTime = opcServer.StartTime; serverInfo.ServerVersion = opcServer.MajorVersion.ToString() + "." + opcServer.MinorVersion.ToString() + "." + opcServer.BuildNumber.ToString(); return(serverInfo); }
private void frmMonitor_Load(object sender, EventArgs e) { AddDicKeyValue(); try { dtCraneError = bll.FillDataTable("WCS.SelectCraneWarning"); for (int i = 1; i <= 5; i++) { Control[] ctl = this.Controls.Find("picCrane" + i.ToString(), true); if (ctl.Length > 0) { ((PictureBox)ctl[0]).Parent = pictureBox1; ((PictureBox)ctl[0]).BackColor = Color.Transparent; } } for (int i = 101; i <= 120; i++) { Control[] ctl = this.Controls.Find("picCar" + i.ToString(), true); if (ctl.Length > 0) { ((PictureBox)ctl[0]).Visible = false; ((PictureBox)ctl[0]).Parent = pictureBox1; ((PictureBox)ctl[0]).BackColor = Color.Transparent; } } PLCS.OnPLC += new PLCEventHandler(Monitor_OnPLC); Cranes.OnCrane += new CraneEventHandler(Monitor_OnCrane); ServerInfo[] Servers = new MonitorConfig("Monitor.xml").Servers; for (int i = 0; i < Servers.Length; i++) { OPCServer opcServer = new OPCServer(Servers[i].Name); opcServer.Connect(Servers[i].ProgID, Servers[i].ServerName);// opcServer.Connect(config.ConnectionString); OPCGroup group = opcServer.AddGroup(Servers[i].GroupName, Servers[i].UpdateRate); foreach (ItemInfo item in Servers[i].Items) { group.AddItem(item.ItemName, item.OpcItemName, item.ClientHandler, item.IsActive); } if (Servers[i].Name == "CarServer") { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(CarServer_OnDataChanged); } else { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(CraneServer_OnDataChanged); } } tmCrane.Interval = 2000; tmCrane.Elapsed += new System.Timers.ElapsedEventHandler(tmCraneWorker); tmCrane.Start(); } catch (Exception ex) { Logger.Error("监控界面中frmMonitor_Load出现异常" + ex.Message); } }
private void btnBuild_Click(object sender, EventArgs e) { OPCServer server = new OPCServer(); try { server.Connect("Kepware.KEPServerEX.V6", "localhost"); MessageBox.Show("连接成功"); } catch (Exception ex) { MessageBox.Show(ex.Message); } groups = server.OPCGroups; //拿到组jih groups.DefaultGroupIsActive = true; //设置组集合默认为激活状态 groups.DefaultGroupDeadband = 0; //设置死区 groups.DefaultGroupUpdateRate = 200; //设置更新频率 group = server.OPCGroups.Add("OPCDOTNETGROUP"); group.IsSubscribed = true; //是否为订阅 group.UpdateRate = 200; //刷新频率 group.DataChange += MyOpcGroup_DataChange;; //组内数据变化的回调函数 group.AsyncReadComplete += MyOpcGroup_AsyncReadComplete; //异步读取完成回调 group.AsyncWriteComplete += MyOpcGroup_AsyncWriteComplete; //异步写入完成回调 group.AsyncCancelComplete += MyOpcGroup_AsyncCancelComplete; //异步取消读取、写入回调 List <string> tags = new List <string>(); tags.Add("汽车机械采样机.#1采样机.ss"); tags.Add("汽车机械采样机.#1采样机.采样机急停"); //tags.Add("汽车机械采样机.#1采样机.ss"); //item = group.OPCItems.AddItem("汽车机械采样机.#1采样机._System._DeviceId", 1); //for (int i = 0; i < tags.Count; i++) //{ // item = group.OPCItems.AddItem(tags[i], i); //} int[] tmpCHandles = new int[3]; for (int i = 0; i < tmpCHandles.Length; i++) { tmpCHandles[i] = i; } string[] tmpIDs = new string[3]; tmpIDs[1] = "汽车机械采样机.#1采样机._System._DemandPoll"; tmpIDs[2] = "汽车机械采样机.#1采样机._System._AutoDemoted"; strItemIDs = (Array)tmpIDs; //必须转成Array型,否则不能调用AddItems方法 lClientHandles = (Array)tmpCHandles; // 添加opc标签 group.OPCItems.AddItems(2, ref strItemIDs, ref lClientHandles, out lserverhandles, out lErrors, RequestedDataTypes, AccessPaths); //items = group.OPCItems; //item = group.OPCItems.AddItem("Channel1.Device1.tag2", 1); //if (dataTesterDAO.CreateTrainCarriagePass(txtMachineCode.Text.Trim(), txtCarNumber.Text.Trim(), cmbDirection.Text)) //{ // MessageBox.Show("生成成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //} }
public OPCConnection(string ProgID) { server = new OPCServer(); server.ClientName = ClientName; server.Connect(ProgID, null); group = server.OPCGroups.Add(GroupName); group.IsSubscribed = true; }
void ConnectToOPC() { //CONNECT TO OPC SERVER ObjOPCServer = new OPCServer(); _serverName = Globals.OPC_SERVER_NAME; //_serverName = "Matrikon.OPC.SiemensPLC.1"; ObjOPCServer.Connect(_serverName, ""); ObjOPCGroups = ObjOPCServer.OPCGroups; }
private OpcMain(OPCServer opcServer, RedisClient redisClient) { Log.Info("进入私有构造器初始化"); _opcServer = opcServer; _dic = new Dictionary <int, string>(); _serviceDic = new Dictionary <int, string>(); _client = redisClient; log4net.Config.XmlConfigurator.Configure(); }
/// <summary> /// Opc와 연결을 합니다. /// </summary> /// <returns></returns> public override bool Open() { string strMsg = string.Format("(Node:{0} / ProgID : {1} )", strIp, ProgId); try { if (Opc != null) { close(); } Opc = new OPCServer(); Opc.Connect(ProgId, (object)strIp); //OpcGrp = new OPCGroup(); OpcGrp = Opc.OPCGroups.Add(strGrpName); OpcGrp.IsActive = true; OpcGrp.UpdateRate = intUpdateRate; OpcGrp.IsSubscribed = true; OpcGrp.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OpcGrp_DataChange); //opc 연결상태 체크 Timer를 시작한다. if (this.tmrOpcCheck != null) { tmrOpcCheck.Dispose(); tmrOpcCheck = null; } // this.bolOpcStatus = true; // this.ChConnection_Status(bolOpcStatus); tmrOpcCheck = new Timer(new TimerCallback(tmrCheckOpcStatus), null, 0, intUpdateRate); //this.ChConnection_Status(true); strMsg = "Open 성공" + strMsg; return(true); } catch (System.Runtime.InteropServices.ExternalException ex) { //activex이기 때문에 에러 발생이 제대로 되지 않아 몇가지만... strMsg = "Open 실패 :" + ex.Message + strMsg + "\r\n" + ex.ToString(); throw ComException(ex, string.Empty); } catch (Exception ex) { strMsg = "Open 실패 :" + ex.Message + strMsg + "\r\n" + ex.ToString(); throw ex; } finally { PLCModule.clsPLCModule.LogWrite("Open", strMsg); } }
private void frmMonitorA_Load(object sender, EventArgs e) { DataTable dt = Program.dtUserPermission; //监控任务--取消堆垛机任务 string filter = "SubModuleCode='MNU_W00A_00A' and OperatorCode='1'"; DataRow[] drs = dt.Select(filter); if (drs.Length <= 0) { this.btnCancel1.Visible = false; this.btnCancel2.Visible = false; this.btnCancel3.Visible = false; this.btnCancel4.Visible = false; } else { this.btnCancel1.Visible = true; this.btnCancel2.Visible = true; this.btnCancel3.Visible = true; this.btnCancel4.Visible = true; } Cranes.OnCrane += new CraneEventHandler(Monitor_OnCrane); InitialP1 = btnSRM1.Location; InitialP2 = btnSRM2.Location; InitialP3 = btnSRM3.Location; InitialP4 = btnSRM4.Location; AddDicKeyValue(); try { ServerInfo[] Servers = new MonitorConfig("MonitorA.xml").Servers; for (int i = 0; i < Servers.Length; i++) { OPCServer opcServer = new OPCServer(Servers[i].Name); opcServer.Connect(Servers[i].ProgID, Servers[i].ServerName);// opcServer.Connect(config.ConnectionString); OPCGroup group = opcServer.AddGroup(Servers[i].GroupName, Servers[i].UpdateRate); foreach (ItemInfo item in Servers[i].Items) { group.AddItem(item.ItemName, item.OpcItemName, item.ClientHandler, item.IsActive); } if (Servers[i].Name.IndexOf("PLC") >= 0) { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(Crane_OnDataChanged); } } } catch (Exception ex) { Logger.Error(ex.Message); } tmWorkTimer.Interval = Program.SendInterval; tmWorkTimer.Elapsed += new System.Timers.ElapsedEventHandler(tmWorker); tmWorkTimer.Start(); }
/// <summary> /// 展开OPC服务器的节点 /// </summary> /// <param name="opcServer">OPC服务器</param> /// <returns>返回展开后的节点数据</returns> public OPCBrowser RecurBrowse(OPCServer opcServer) { OPCBrowser opcBrowser = opcServer.CreateBrowser(); //展开分支 opcBrowser.ShowBranches(); //展开叶子 opcBrowser.ShowLeafs(true); return(opcBrowser); }
public UnNormalFm() { InitializeComponent(); UpdateControlEnable(false, BtnEnd); Initdata(); TimeToClike.Start(); opcServer = new OPCServer(); handle += UpdateListBox; ListLineNum.Add("1"); }
/// <summary> /// 创建服务 /// </summary> /// <returns></returns> private bool CreateServer() { // try { opcServer = new OPCServer(); // } // catch { // return false; // } return(true); }
/// <summary> /// 连接OPC Server /// </summary> /// <returns></returns> public bool ConnectToServer() { try { if (OpcServer != null) { try { if (OpcServer.ServerState == (int)OPCServerState.OPCRunning) { //WriteLog.WriteLogs(OpcServer.ServerName + "-----" + OpcServer.ServerNode + "-----" + OpcServer.ServerState); OPCState = true; return(true); } } catch { OPCState = false; } } bool isConn = false; OpcServer = new OPCServer(); //获取IP地址上最后一个 OPC Server 的名字 object serverList = OpcServer.GetOPCServers(IpAddr); if (serverList == null) { OPCState = false; return(false); } foreach (string turn in (Array)serverList) { ServerName = turn; } OpcServer.Connect(ServerName, IpAddr); //连接OPC Server if (OpcServer.ServerState == (int)OPCServerState.OPCRunning) { isConn = true; IsConnected = true; OPCState = true; } return(isConn); } catch (Exception ex) { Console.WriteLine(ex.ToString()); // WriteLog.WriteLogs(ex.ToString()); OPCState = false; return(false); } }
/// <summary> /// 确定本地主机时,动态改变连接的kepServer主机名 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmb_ServerNode_SelectedIndexChanged(object sender, EventArgs e) { this.cmb_ServerName.Items.Clear(); kepServer = new OPCServer(); object serverList = kepServer.GetOPCServers(this.cmb_ServerNode.Text.Trim()); foreach (var item in (Array)serverList) { this.cmb_ServerName.Items.Add(item); } }
//創建Server private bool CreateServer() { try { opcServer = new OPCServer(); } catch { return(false); } return(true); }
public StatusCode getForecast(RequestContext context, OPCServer.WeatherStationModel model) { Console.WriteLine("Calling getForecast"); lock (model) { Weather.getForecast(); model.Forecast = Weather.Forecast; Weather.forecastPrintToFile(); } return StatusCodes.Good; }
public StatusCode getConditions(RequestContext context, OPCServer.WeatherStationModel model) { Console.WriteLine("Calling getConditions"); lock (model) { Weather.getCurrentConditions(); model.Conditions = Weather.Conditions; Weather.conditionsPrintToFile(); } return StatusCodes.Good; }
/// <summary> /// 获取OPC服务名称 /// </summary> /// <param name="serverIP">服务器IP</param> /// <returns></returns> public List <string> GetOPCServerNames(string serverIP) { OPCServer opcServer = new OPCServer(); List <string> lst = new List <string>(); object serverList = opcServer.GetOPCServers(serverIP); foreach (string item in (Array)serverList) { lst.Add(item); } return(lst); }
public OPCServer UpdateOPCServer(OPCServer newOPCServer) { try { _opcServerDal.Update(newOPCServer); } catch (RepositoryException ex) { throw new AisinoMesServiceException("更新opcserver出错", ex.InnerException); } return(newOPCServer); }
public OPCSystem(string strOPCName, string hostIp, string serverName) : base(strOPCName) { opcServer = new OPCServer(); object serverList = opcServer.GetOPCServers(hostIp); foreach (string turn in (Array)serverList) { strServerList.Add(turn); } strHostIp = hostIp; strServerName = serverName; }
public OPCBrowser CreateOPCBrowser(OPCServer opcServer) { try { return(opcServer.CreateBrowser()); } catch (Exception err) { Console.WriteLine("创建opcBrowser出错" + err.Message); return(null); } }
public string GetServerInfo(OPCServer opcServer) { try { return(opcServer.StartTime.ToString() + "." + opcServer.MajorVersion.ToString() + "." + opcServer.MinorVersion.ToString() + "." + opcServer.BuildNumber.ToString()); } catch (Exception err) { Console.WriteLine("获取服务器信息异常" + err.Message); return(null); } }
/// <summary> /// Подключается к OPC-серверу и запускает рекурсивный обход его содержимого. /// </summary> /// <param name="aHost">Хост.</param> /// <param name="aOpcServerName">Имя OPC-сервера.</param> private static void ShowOpcTagsList(string aHost, string aOpcServerName) { var opcServer = new OPCServer(); try { opcServer.Connect(aOpcServerName, aHost); } catch (COMException ex) { Console.WriteLine("Не удалось подключиться к OPC-серверу по адресу {0}. Ошибка: {1}.", aHost, ex.Message); return; } ShowOpcTagsRecurcive(opcServer.CreateBrowser()); }
public OpcValueImpl( OPCServer aServer, string aName = "", OPCDataSource aSource = OPCDataSource.OPCCache, int aUpdateRate = 100) { if (aServer == null) { throw new ArgumentNullException("aServer"); } Source = aSource; server = aServer; Name = aName; UpdateRate = aUpdateRate; }
/// <summary> /// Показывает все доступные OPC-сервера на хосте. /// </summary> /// <param name="aHost">Хост.</param> private static void ShowOpcServerNames(string aHost) { try { var serversNames = new OPCServer().GetOPCServers(aHost) as Array; if (serversNames != null && serversNames.Length > 0) { Console.WriteLine("Список всех OPC-серверов по адресу {0}:", aHost); for (var i = 1; i <= serversNames.Length; ++i) { Console.WriteLine("{0} {1}", i, serversNames.GetValue(i)); } } else { Console.WriteLine("OPC-серверов по адресу {0} не найдено.", aHost); } } catch (COMException ex) { Console.WriteLine("COM-ошибка при просмотре списка OPC-серверов: " + ex.Message); } }
protected override void DoInitialize() { logger.Info("Инициализация..."); server = new OPCServer(); var serverName = opcConfiguration.GetServer(); var serverHost = opcConfiguration.GetHost(); server.Connect(serverName, serverHost); try { InitializeControlBlock(); InitializeOpcSensors(); InitializeActivator(); } catch (Exception ex) { logger.Error("Ошибка при инициализации: " + ex.Message); } lastDataBlock = controlBlock.DataBlocksCount - 1; opcReadingThread = new Thread(DataBlockReading); opcReadingThread.Start(); logger.Info("Инициализация завершена."); }
//枚举本地OPC服务器 private void GetLocalServer() { //获取本地计算机IP,计算机名称 //IPHostEntry IPHost = Dns.Resolve(Environment.MachineName); IPHostEntry ipHost = Dns.GetHostEntry(Environment.MachineName); if (ipHost.AddressList.Length > 0) { _strHostIp = ipHost.AddressList[0].ToString(); } else { return; } //通过IP来获取计算机名称,可用在局域网内 IPHostEntry ipHostEntry = Dns.GetHostEntry(_strHostIp); _strHostName = ipHostEntry.HostName; //获取本地计算机上的OPCServerName try { _kepServer = new OPCServer(); object serverList = _kepServer.GetOPCServers(_strHostName); foreach (string turn in (Array)serverList) { ComboBox1.Items.Add(turn); } ComboBox1.SelectedIndex = 0; } catch (Exception err) { MessageBox.Show("枚举本地OPC服务器出错:" + err.Message, "提示信息", MessageBoxButton.OK, MessageBoxImage.Warning); } }
//关闭窗体时处理的事情 private void Window_Closing(object sender, CancelEventArgs e) { MessageBoxResult key = MessageBox.Show( "确定退出吗", "确定", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); e.Cancel = (key == MessageBoxResult.No); if (!_opcConnected) { return; } if (_kepGroup != null) { _kepGroup.DataChange -= KepGroup_DataChange; } if (_kepServer != null) { _kepServer.Disconnect(); _kepServer = null; } _opcConnected = false; Application.Current.Shutdown(); }
void init() { server = new OPCServer(); server.Connect(opcname); statusGroup= server.OPCGroups.Add(); statusGroup.OPCItems.AddItem(VB30ITEM, 1); statusGroup.OPCItems.AddItem(VB80ITEM, 2); resultGroup = server.OPCGroups.Add(); resultGroup.OPCItems.AddItem(I04_I15,1); CommandGroup = server.OPCGroups.Add(); CommandGroup.OPCItems.AddItem(START,1); CommandGroup.OPCItems.AddItem(PAUSE, 2); CommandGroup.OPCItems.AddItem(RESET, 3); statusGroup.DataChange += statusGroup_DataChange; //resultGroup.DataChange += resultGroup_DataChange; CommandGroup.DataChange += CommandGroup_DataChange; #region statusGroup.IsSubscribed = true; //resultGroup.IsSubscribed = true; CommandGroup.IsSubscribed = true; resultGroup.IsActive = true; statusGroup.IsActive = true; CommandGroup.IsActive = true; resultGroup.UpdateRate = 10; statusGroup.UpdateRate = 10; CommandGroup.UpdateRate = 10; #endregion toolStripProgressBar1.Step = 1; toolStripProgressBar1.Maximum = 19; }
private void Opc2Modbus_Load(object sender, EventArgs e) { if (ReadItemsCSV()) { // Visualize only in nofification bar. this.Hide(); this.WindowState = FormWindowState.Minimized; //Subscrib to OPC Server try { ObjOPCServer = new OPCServer(); ObjOPCGroup = new OPCGroup[Compressors]; String GroupName; //Conect to the server ObjOPCServer.Connect("POPCS.DAServer.1"); //Create a group ObjOPCGroups = ObjOPCServer.OPCGroups; for (int c = 0; c < Compressors; c++) { GroupName = "C" + (c + 1).ToString("00"); ObjOPCGroup[c] = ObjOPCGroups.Add(GroupName); //Define event DataChange ObjOPCGroup[c].DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OPCGroup_DataChange); //Define DefaultAccessPath (necessary for POPCS.DAServer.1) ObjOPCGroup[c].OPCItems.DefaultAccessPath = GroupName; //Define Items. for (int i = 1; i <= numItemsCSV; i++) ObjOPCGroup[c].OPCItems.AddItem(Items[(c * numItems) + i].ItemID, (c * numItems) + i); //Group properties ObjOPCGroup[c].UpdateRate = 1000; ObjOPCGroup[c].IsActive = true; ObjOPCGroup[c].IsSubscribed = true; } } catch (Exception ex) { OPC2Modbus.Program.Log.Fatal("Error al suscribirse al servidor OPC", ex); MessageBox.Show("Error al suscribirse al servidor OPC.\n La aplicación va ha cerrarse.", "Error fatal", MessageBoxButtons.OK, MessageBoxIcon.Error); bExit = true; bFatal = true; Application.Exit(); } // Start modbus server. try { modbusServer.Listen(); } catch (Exception ex) { OPC2Modbus.Program.Log.Fatal("Error al iniciar el servidor Modbus TCP", ex); MessageBox.Show("Error al iniciar el servidor Modbus TCP.\n La aplicación va ha cerrarse.", "Error fatal", MessageBoxButtons.OK, MessageBoxIcon.Error); bExit = true; bFatal = true; Application.Exit(); } } }
public void SetOpcServer(OPCServer aOpcServer) { server = aOpcServer; }
/// <summary> /// 构造函数 /// </summary> public OPCClass() { //初始化变量 fOPCServer = new OPCServer(); fIsConnect = false; fOPCItemList = new List<OPCItemList>(); }
public bool Connect() { try { IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP); strHostName = ipHostEntry.HostName.ToString(); MyServer = new OPCServer(); try { MyServer.Connect(serverProgID, strHostIP);//连接服务器:服务器名+主机名或IP if ((MyServer.ServerState == (int)OPCServerState.OPCFailed) && (MyServer.ServerState == (int)OPCServerState.OPCDisconnected)) { Console.WriteLine("已连接到:{0}::{1}",strHostIP, MyServer.ServerName); Console.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); try { sw = File.AppendText(logfile); sw.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); sw.WriteLine("已连接到:{0}::{1}", strHostIP, MyServer.ServerName); sw.Close(); } catch { } opc_connected = true; } else { //这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档 Console.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); opc_connected = false; try { sw = File.AppendText(logfile); sw.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); sw.Close(); } catch { } } //MyServer.ServerShutDown += DisConnect;//服务器断开事件 } catch (Exception err) { Console.WriteLine("连接远程服务器出现错误:{0}" + err.Message); try { sw = File.AppendText(logfile); sw.WriteLine("连接远程服务器出现错误:{0}" + err.Message); sw.Close(); } catch { } opc_connected = false; return false; } try { MyGroup = MyServer.OPCGroups.Add("sac_opc");//添加组 //以下设置组属性 { MyServer.OPCGroups.DefaultGroupIsActive = true;//激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;// 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200;//默认组群的刷新频率为200ms MyGroup.UpdateRate = 1000;//刷新频率为1秒。 //MyGroup.IsSubscribed = true;//使用订阅功能,即可以异步,默认false } MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); //MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete); } catch (Exception err) { Console.WriteLine("创建组出现错误:{0}", err.Message); try { sw = File.AppendText(logfile); sw.WriteLine("创建组出现错误:{0}", err.Message); sw.Close(); } catch { } return false; } return true; } catch (Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); return false; } tmConnect = new System.Timers.Timer(); tmConnect.AutoReset = true; tmConnect.Interval = connectRate; tmConnect.Elapsed += new System.Timers.ElapsedEventHandler(tm_Connect); tmConnect.Start(); return true; }