java 连接opc



第一种:用utgard连接opc,以下代码为官方的代码,改为自己的就可以了。

<dependency>
   <groupId>org.openscada.external</groupId>
   <artifactId>org.openscada.external.jcifs</artifactId>
   <version>1.2.25</version>
</dependency>
<dependency>
   <groupId>org.openscada.jinterop</groupId>
   <artifactId>org.openscada.jinterop.core</artifactId>
   <version>2.1.8</version>
</dependency>
<dependency>
   <groupId>org.openscada.jinterop</groupId>
   <artifactId>org.openscada.jinterop.deps</artifactId>
   <version>1.5.0</version>
</dependency>
<dependency>
   <groupId>org.openscada.utgard</groupId>
   <artifactId>org.openscada.opc.dcom</artifactId>
   <version>1.5.0</version>
</dependency>
<dependency>
   <groupId>org.openscada.utgard</groupId>
   <artifactId>org.openscada.opc.lib</artifactId>
   <version>1.5.0</version>
</dependency>
<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcprov-jdk15on</artifactId>
   <version>1.59</version>
</dependency>
public static void main(String[] args) throws Exception{
    final ConnectionInformation ci = new ConnectionInformation();
    ci.setHost("localhost");
    ci.setUser("Administrator");
    ci.setPassword("gl");
    ci.setProgId("Matrikon.OPC.Simulation.1");
    final String itemId = "Bucket Brigade.Int4";
    // create a new server
    final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
    try {
        // connect to server
        server.connect();
        System.out.println("连接成功");
        final AccessBase access = new SyncAccess(server, 500);
        access.addItem(itemId, new DataCallback() {
            @Override
            public void changed(Item item, ItemState state) {
                // also dump value
                try {
                    if (state.getValue().getType() == JIVariant.VT_UI4) {
                        System.out.println("<<< " + state + " / value = " + state.getValue().getObjectAsUnsigned().getValue());
                    } else {
                        System.out.println("<<< " + state + " / ------value = " + state.getValue().getObject());
                    }
                } catch (JIException e) {
                    e.printStackTrace();
                }
            }
        });

        // Add a new group
        final Group group = server.addGroup("test");
        // Add a new item to the group
        final Item item = group.addItem(itemId);

        // start reading
        access.bind();

        // add a thread for writing a value every 3 seconds
        ScheduledExecutorService writeThread = Executors.newSingleThreadScheduledExecutor();
        final AtomicInteger i = new AtomicInteger(0);
        writeThread.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                final JIVariant value = new JIVariant(i.incrementAndGet());
                try {
                    System.out.println(">>> " + "writing value " + i.get());
                    item.write(value);
                } catch (JIException e) {
                    e.printStackTrace();
                }
            }
        }, 5, 3, TimeUnit.SECONDS);

        // wait a little bit
        Thread.sleep(20 * 1000);
        writeThread.shutdownNow();
        // stop reading
        access.unbind();
    } catch (final JIException e) {
        System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
    }
}


第二种:使用jOpc连接 opc服务器,只支持32位的

package com.kaiya.svg.opc;

import javafish.clients.opc.JOpc;
import javafish.clients.opc.asynch.AsynchEvent;
import javafish.clients.opc.asynch.OpcAsynchGroupListener;
import javafish.clients.opc.component.OpcGroup;
import javafish.clients.opc.component.OpcItem;
import javafish.clients.opc.exception.Asynch10ReadException;
import javafish.clients.opc.exception.Asynch10UnadviseException;
import javafish.clients.opc.exception.CoInitializeException;
import javafish.clients.opc.exception.ComponentNotFoundException;
import javafish.clients.opc.exception.ConnectivityException;
import javafish.clients.opc.exception.CoUninitializeException;
import javafish.clients.opc.exception.GroupActivityException;
import javafish.clients.opc.exception.GroupUpdateTimeException;
import javafish.clients.opc.exception.UnableAddGroupException;
import javafish.clients.opc.exception.UnableAddItemException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

public class AsynchReadAndGroupActivityExample {

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        AsynchReadAndGroupActivityExample test = new AsynchReadAndGroupActivityExample();

        try {
            /**初始化服务**/
            JOpc.coInitialize();
        }
        catch (CoInitializeException e1) {
            e1.printStackTrace();
        }
        /**建立server对象jopc(IP ,OPCServer名称 ,任意)**/
        JOpc jopc = new JOpc("localhost", "Matrikon.OPC.Simulation.1", "JOPC1");

        /**建立一个组((用户组的标识名称),开始活动的组(true 开始 false 不开始) 默认true,刷新组的时间 毫秒,默认 0.0f)**/
        OpcGroup group = new OpcGroup("test", true, 20, 0.0f);

        /**name属性表示OPC服务器中的ItemID**/
        OpcItem item1 = new OpcItem("Bucket Brigade.Int1", true, "");
        OpcItem item2 = new OpcItem("Bucket Brigade.Int4", true, "");

        /**添加到组**/
        group.addItem(item1);
        group.addItem(item2);

        jopc.addGroup(group);

        try {
            /**调用JCustomOpc.connect()连接服务器**/
            jopc.connect();
            System.out.println("OPC client is connected...");
            System.out.println("OPC 服务器连接成功...");

            /** 调用JOpc.registerGroups()注册所有的组使用registerGroups()方法注册则OpcItem不用单独注册。如果调用registerGroup(OpcGroup)注册OpcGroup,则还需调用registerItem(OpcGroup,OpcItem)**/
            jopc.registerGroups();
            System.out.println("OPC groups are registered...");
            System.out.println("OPC groups 注册成功...");

            /** 调用JOpc.asynch10Read()异步读数据**/
            jopc.asynch10Read(group);
            System.out.println("OPC asynchronous reading is applied...");
            System.out.println("OPC 正在异步读取数据...");

            OpcGroup downGroup;

            /**当前时间秒数**/
            long start = System.currentTimeMillis();
            while ((System.currentTimeMillis() - start) < 10000) {
                jopc.ping();
                downGroup = jopc.getDownloadGroup();
                if (downGroup != null) {
                    System.out.println(downGroup);
                }

                if ((System.currentTimeMillis() - start) >= 6000) {
                    jopc.setGroupActivity(group, false);
                }
                synchronized(test) {
                    /**间隔50毫秒**/
                    test.wait(1000);
                }
            }

            // change activity
            jopc.setGroupActivity(group, true);

            // change updateTime
            jopc.setGroupUpdateTime(group, 100);

            start = System.currentTimeMillis();
            while ((System.currentTimeMillis() - start) < 10000) {
                jopc.ping();
                downGroup = jopc.getDownloadGroup();
                if (downGroup != null) {
                    System.out.println(downGroup);
                }

                synchronized(test) {
                    test.wait(2000);
                }
            }
            /**断开异步读取**/
            jopc.asynch10Unadvise(group);
            System.out.println("OPC asynchronous reading is unadvise...");
            System.out.println("OPC 断开异步读取...");
            /**断开连接**/
            JOpc.coUninitialize();
            System.out.println("Program terminated...");
            System.out.println("断开服务器连接...");
        }
        catch (ConnectivityException e) {
            e.printStackTrace();
        }
        catch (UnableAddGroupException e) {
            e.printStackTrace();
        }
        catch (UnableAddItemException e) {
            e.printStackTrace();
        }
        catch (ComponentNotFoundException e) {
            e.printStackTrace();
        }
        catch (Asynch10ReadException e) {
            e.printStackTrace();
        }
        catch (Asynch10UnadviseException e) {
            e.printStackTrace();
        }
        catch (GroupUpdateTimeException e) {
            e.printStackTrace();
        }
        catch (GroupActivityException e) {
            e.printStackTrace();
        }
        catch (CoUninitializeException e) {
            e.printStackTrace();
        }
    }

}


如果报这样的错:

Property file javafish.clients.opc.JCustomOpc doesn't exist. System terminated
那你就建立
javafish.clients.opc

这个文件夹,把JCustomOpc.properties  文件放入下面,文件内容如下


在与src同目录下建立lib文件夹,放入JCustomOpc.dll  文件(自己下吧),当然你还需要jeasyopc.jar文件。


难得写还是给你个链接吧: https://download.csdn.net/download/qq_37838223/10465135






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值