Add utgard testcases

This commit is contained in:
luoyan35714 2014-12-03 16:34:42 +08:00
parent ec263090a3
commit 19aa54799d
27 changed files with 1675 additions and 0 deletions

4
.gitignore vendored
View File

@ -10,3 +10,7 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
.settings/
bin/
target/

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="resources/|main/" kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src/resources"/>
<classpathentry kind="src" path="src/main"/>
<classpathentry kind="lib" path="lib/commons-logging-1.1.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.13.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OPC_Client_Jeasyopc</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,19 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.freud.opc</groupId>
<artifactId>OPC_Client_Jeasyopc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="lib/j-interop.jar"/>
<classpathentry kind="lib" path="lib/j-interopdeps.jar"/>
<classpathentry kind="lib" path="lib/jcifs-1.2.19.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.16.jar"/>
<classpathentry kind="lib" path="lib/org.openscada.opc.dcom_1.1.0.v20130529.jar"/>
<classpathentry kind="lib" path="lib/org.openscada.opc.lib_1.1.0.v20130529.jar"/>
<classpathentry kind="lib" path="lib/slf4j-api-1.7.6.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>OPC_Client_Utgard</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1 @@
2014-12-03 16:22:54,739 INFO com.freud.dcom.utgard.cases.DCOMTest5.main:67 - test

View File

@ -0,0 +1,67 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.da.OPCSERVERSTATUS;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* »ñÈ¡ServerµÄStatusÐÅÏ¢
*
* @author Freud
*
*/
public class DCOMTest1 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
dumpServerStatus(server);
}
public static void dumpServerStatus(final OPCServer server)
throws JIException {
final OPCSERVERSTATUS status = server.getStatus();
System.out.println("===== SERVER STATUS ======");
System.out.println("State: " + status.getServerState().toString());
System.out.println("Vendor: " + status.getVendorInfo());
System.out.println(String.format("Version: %d.%d.%d",
status.getMajorVersion(), status.getMinorVersion(),
status.getBuildNumber()));
System.out.println("Groups: " + status.getGroupCount());
System.out.println("Bandwidth: " + status.getBandWidth());
System.out.println(String.format("Start Time: %tc", status
.getStartTime().asCalendar()));
System.out.println(String.format("Current Time: %tc", status
.getCurrentTime().asCalendar()));
System.out.println(String.format("Last Update Time: %tc", status
.getLastUpdateTime().asCalendar()));
System.out.println("===== SERVER STATUS ======");
}
}

View File

@ -0,0 +1,128 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.net.UnknownHostException;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.dcom.da.OPCBROWSEDIRECTION;
import org.openscada.opc.dcom.da.OPCBROWSETYPE;
import org.openscada.opc.dcom.da.OPCNAMESPACETYPE;
import org.openscada.opc.dcom.da.impl.OPCBrowseServerAddressSpace;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* 遍历OPC连接下的所有Group和Item
*
* @author Freud
*
*/
public class DCOMTest2 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
final OPCBrowseServerAddressSpace serverBrowser = server.getBrowser();
/**
* Flat形式获取所有Item信息
*/
browseFlat(serverBrowser);
/**
* 获取所有的Group和Item信息
*/
browseTree(serverBrowser);
}
/**
* Tree形式获取所有Group和Item的信息
*/
private static void browseTree(final OPCBrowseServerAddressSpace browser)
throws IllegalArgumentException, UnknownHostException, JIException {
System.out.println("Showing hierarchial address space");
System.out.println(String.format("Organization: %s",
browser.queryOrganization()));
if (!browser.queryOrganization().equals(
OPCNAMESPACETYPE.OPC_NS_HIERARCHIAL)) {
return;
}
browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_TO);
browseTree(browser, 0);
}
private static String printTab(int level) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < level; i++) {
sb.append("\t");
}
return sb.toString();
}
private static void browseTree(final OPCBrowseServerAddressSpace browser,
final int level) throws JIException, IllegalArgumentException,
UnknownHostException {
for (final String item : browser.browse(OPCBROWSETYPE.OPC_LEAF, "", 0,
JIVariant.VT_EMPTY).asCollection()) {
System.out.println(printTab(level) + "Leaf: " + item + "\tName: "
+ browser.getItemID(item));
}
for (final String item : browser.browse(OPCBROWSETYPE.OPC_BRANCH, "",
0, JIVariant.VT_EMPTY).asCollection()) {
System.out.println(printTab(level) + "Branch: " + item);
browser.changePosition(item, OPCBROWSEDIRECTION.OPC_BROWSE_DOWN);
browseTree(browser, level + 1);
browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_UP);
}
}
/**
* Flat形式获取Item的信息
*/
private static void browseFlat(final OPCBrowseServerAddressSpace browser)
throws JIException, IllegalArgumentException, UnknownHostException {
System.out.println(String.format("Organization: %s",
browser.queryOrganization()));
browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_TO);
System.out.println("Showing flat address space");
for (final String id : browser.browse(OPCBROWSETYPE.OPC_FLAT, "", 0,
JIVariant.VT_EMPTY).asCollection()) {
System.out.println("Item: " + id);
}
}
}

View File

@ -0,0 +1,81 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.net.UnknownHostException;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.da.OPCENUMSCOPE;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* 通过Scope遍历OPC连接下的所有Group信息
*
* @author Freud
*
*/
public class DCOMTest3 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
/**
* 添加一个Group的信息
*/
OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
0.0f, 1033);
enumerateGroups(server, OPCENUMSCOPE.OPC_ENUM_PUBLIC);
enumerateGroups(server, OPCENUMSCOPE.OPC_ENUM_PRIVATE);
enumerateGroups(server, OPCENUMSCOPE.OPC_ENUM_ALL);
// clean up
server.removeGroup(group, true);
}
/**
* 通过Scope查找并遍历Groups的信息
*
* @param server
* @param scope
* @throws IllegalArgumentException
* @throws UnknownHostException
* @throws JIException
*/
public static void enumerateGroups(final OPCServer server,
final OPCENUMSCOPE scope) throws IllegalArgumentException,
UnknownHostException, JIException {
System.out.println("Enum Groups: " + scope.toString());
for (final String group : server.getGroups(scope).asCollection()) {
System.out.println("Group: " + group);
}
}
}

View File

@ -0,0 +1,221 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.common.EventHandler;
import org.openscada.opc.dcom.common.KeyedResult;
import org.openscada.opc.dcom.common.KeyedResultSet;
import org.openscada.opc.dcom.common.Result;
import org.openscada.opc.dcom.common.ResultSet;
import org.openscada.opc.dcom.common.impl.OPCCommon;
import org.openscada.opc.dcom.da.OPCDATASOURCE;
import org.openscada.opc.dcom.da.OPCITEMDEF;
import org.openscada.opc.dcom.da.OPCITEMRESULT;
import org.openscada.opc.dcom.da.OPCITEMSTATE;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCItemMgt;
import org.openscada.opc.dcom.da.impl.OPCServer;
import org.openscada.opc.dcom.da.impl.OPCSyncIO;
/**
* 通过Scope遍历OPC连接下的所有Group信息
*
* @author Freud
*
*/
public class DCOMTest4 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
/**
* 添加一个Group的信息
*/
OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
0.0f, 1033);
testItems(server, group, new String[] { "Saw-toothed Waves.Int2",
"Saw-toothed Waves.test2" });
// clean up
server.removeGroup(group, true);
}
private static void showError(final OPCCommon common, final int errorCode)
throws JIException {
System.out.println(String.format("Error (%X): '%s'", errorCode,
common.getErrorString(errorCode, 1033)));
}
private static void showError(final OPCServer server, final int errorCode)
throws JIException {
showError(server.getCommon(), errorCode);
}
private static boolean dumpOPCITEMRESULT(
final KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result) {
int failed = 0;
for (final KeyedResult<OPCITEMDEF, OPCITEMRESULT> resultEntry : result) {
System.out.println("==================================");
System.out.println(String.format("Item: '%s' ", resultEntry
.getKey().getItemID()));
System.out.println(String.format("Error Code: %08x",
resultEntry.getErrorCode()));
if (!resultEntry.isFailed()) {
System.out.println(String.format("Server Handle: %08X",
resultEntry.getValue().getServerHandle()));
System.out.println(String.format("Data Type: %d", resultEntry
.getValue().getCanonicalDataType()));
System.out.println(String.format("Access Rights: %d",
resultEntry.getValue().getAccessRights()));
System.out.println(String.format("Reserved: %d", resultEntry
.getValue().getReserved()));
} else {
failed++;
}
}
return failed == 0;
}
private static void testItems(final OPCServer server,
final OPCGroupStateMgt group, final String... itemIDs)
throws IllegalArgumentException, UnknownHostException, JIException {
final OPCItemMgt itemManagement = group.getItemManagement();
final List<OPCITEMDEF> items = new ArrayList<OPCITEMDEF>(itemIDs.length);
for (final String id : itemIDs) {
final OPCITEMDEF item = new OPCITEMDEF();
item.setItemID(id);
item.setClientHandle(new Random().nextInt());
items.add(item);
}
final OPCITEMDEF[] itemArray = items.toArray(new OPCITEMDEF[0]);
System.out.println("Validate");
KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result = itemManagement
.validate(itemArray);
if (!dumpOPCITEMRESULT(result)) {
return;
}
// now add them to the group
System.out.println("Add");
result = itemManagement.add(itemArray);
if (!dumpOPCITEMRESULT(result)) {
return;
}
// get the server handle array
final Integer[] serverHandles = new Integer[itemArray.length];
for (int i = 0; i < itemArray.length; i++) {
serverHandles[i] = new Integer(result.get(i).getValue()
.getServerHandle());
}
// set them active
System.out.println("Activate");
final ResultSet<Integer> resultSet = itemManagement.setActiveState(
true, serverHandles);
for (final Result<Integer> resultEntry : resultSet) {
System.out.println(String.format("Item: %08X, Error: %08X",
resultEntry.getValue(), resultEntry.getErrorCode()));
}
// set client handles
System.out.println("Set client handles");
final Integer[] clientHandles = new Integer[serverHandles.length];
for (int i = 0; i < serverHandles.length; i++) {
clientHandles[i] = i;
}
itemManagement.setClientHandles(serverHandles, clientHandles);
System.out.println("Create async IO 2.0 object");
// OPCAsyncIO2 asyncIO2 = group.getAsyncIO2 ();
// connect handler
System.out.println("attach");
final EventHandler eventHandler = group.attach(new DumpDataCallback());
// sleep
try {
System.out.println("Waiting...");
Thread.sleep(10 * 1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
eventHandler.detach();
// sync IO - read
final OPCSyncIO syncIO = group.getSyncIO();
// OPCAsyncIO2 asyncIO2 = group.getAsyncIO2 ();
/*
* System.out.println ( "attach..enable" ); asyncIO2.setEnable ( true );
* System.out.println ( "attach..refresh" ); asyncIO2.refresh (
* (short)1, 1 );
*/
final KeyedResultSet<Integer, OPCITEMSTATE> itemState = syncIO.read(
OPCDATASOURCE.OPC_DS_DEVICE, serverHandles);
for (final KeyedResult<Integer, OPCITEMSTATE> itemStateEntry : itemState) {
final int errorCode = itemStateEntry.getErrorCode();
System.out
.println(String
.format("Server ID: %08X, Value: %s, Timestamp: %d/%d (%Tc), Quality: %d, Error: %08X",
itemStateEntry.getKey(), itemStateEntry
.getValue().getValue(),
itemStateEntry.getValue().getTimestamp()
.getHigh(),
itemStateEntry.getValue().getTimestamp()
.getLow(), itemStateEntry
.getValue().getTimestamp()
.asCalendar(), itemStateEntry
.getValue().getQuality(), errorCode));
if (errorCode != 0) {
showError(server, errorCode);
}
}
// set them inactive
System.out.println("In-Active");
itemManagement.setActiveState(false, serverHandles);
// finally remove them again
System.out.println("Remove");
itemManagement.remove(serverHandles);
}
}

View File

@ -0,0 +1,119 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.dcom.common.KeyedResult;
import org.openscada.opc.dcom.common.KeyedResultSet;
import org.openscada.opc.dcom.da.PropertyDescription;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCItemProperties;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* 获取指定Item的Properties
*
* @author Freud
*
*/
public class DCOMTest5 {
private static Logger LOGGER = Logger.getLogger(DCOMTest5.class);
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
/**
* 添加一个Group的信息
*/
OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
0.0f, 1033);
final OPCItemProperties itemProperties = server
.getItemPropertiesService();
dumpItemProperties(itemProperties, "Saw-toothed Waves.Int");
// clean up
server.removeGroup(group, true);
LOGGER.info("test");
}
public static void dumpItemProperties(
final OPCItemProperties itemProperties, final String itemID)
throws JIException {
final Collection<PropertyDescription> properties = itemProperties
.queryAvailableProperties(itemID);
final int[] ids = new int[properties.size()];
System.out.println(String.format("Item Properties for '%s' (count:%d)",
itemID, properties.size()));
int i = 0;
for (final PropertyDescription pd : properties) {
ids[i] = pd.getId();
System.out.println("ID: " + pd.getId());
System.out.println("Description: " + pd.getDescription());
System.out.println("Variable Type: " + pd.getVarType());
i++;
}
System.out.println("Lookup");
dumpItemPropertiesLookup(itemProperties, itemID, ids);
System.out.println("Query");
dumpItemProperties2(itemProperties, itemID, ids);
}
public static void dumpItemProperties2(
final OPCItemProperties itemProperties, final String itemID,
final int... ids) throws JIException {
final KeyedResultSet<Integer, JIVariant> values = itemProperties
.getItemProperties(itemID, ids);
for (final KeyedResult<Integer, JIVariant> entry : values) {
System.out.println(String.format(
"ID: %d, Value: %s, Error Code: %08x", entry.getKey(),
entry.getValue().toString(), entry.getErrorCode()));
}
}
public static void dumpItemPropertiesLookup(
final OPCItemProperties itemProperties, final String itemID,
final int... ids) throws JIException {
final KeyedResultSet<Integer, String> values = itemProperties
.lookupItemIDs(itemID, ids);
for (final KeyedResult<Integer, String> entry : values) {
System.out.println(String.format(
"ID: %d, Item ID: %s, Error Code: %08x", entry.getKey(),
entry.getValue(), entry.getErrorCode()));
}
}
}

View File

@ -0,0 +1,71 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.util.LinkedList;
import java.util.List;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.da.IORequest;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCItemIO;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* Query指定的Item
*
* @author Freud
*
*/
public class DCOMTest6 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
/**
* 添加一个Group的信息
*/
OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
0.0f, 1033);
final OPCItemIO itemIO = server.getItemIOService();
queryItems(itemIO, "Saw-toothed Waves.Int");
// clean up
server.removeGroup(group, true);
}
public static void queryItems(final OPCItemIO itemIO, final String... items)
throws JIException {
final List<IORequest> requests = new LinkedList<IORequest>();
for (final String item : items) {
requests.add(new IORequest(item, 0));
}
itemIO.read(requests.toArray(new IORequest[0]));
}
}

View File

@ -0,0 +1,201 @@
package com.freud.dcom.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.common.EventHandler;
import org.openscada.opc.dcom.common.KeyedResult;
import org.openscada.opc.dcom.common.KeyedResultSet;
import org.openscada.opc.dcom.common.Result;
import org.openscada.opc.dcom.common.ResultSet;
import org.openscada.opc.dcom.common.impl.OPCCommon;
import org.openscada.opc.dcom.da.OPCDATASOURCE;
import org.openscada.opc.dcom.da.OPCITEMDEF;
import org.openscada.opc.dcom.da.OPCITEMRESULT;
import org.openscada.opc.dcom.da.impl.OPCAsyncIO2;
import org.openscada.opc.dcom.da.impl.OPCAsyncIO2.AsyncResult;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCItemMgt;
import org.openscada.opc.dcom.da.impl.OPCServer;
/**
* 通过Scope遍历OPC连接下的所有Group信息
*
* @author Freud
*
*/
public class DCOMTest7 {
public static void main(String[] args) throws Exception {
JISystem.setAutoRegisteration(true);
/**
* Session获取
*/
JISession _session = JISession.createSession(
getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
getEntryValue(CONFIG_PASSWORD));
final JIComServer comServer = new JIComServer(
JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
getEntryValue(CONFIG_HOST), _session);
final IJIComObject serverObject = comServer.createInstance();
OPCServer server = new OPCServer(serverObject);
/**
* 添加一个Group的信息
*/
OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
0.0f, 1033);
testItems(server, group, new String[] { "Saw-toothed Waves.Int2" });
// clean up
server.removeGroup(group, true);
}
public static void testItems(final OPCServer server,
final OPCGroupStateMgt group, final String... itemIDs)
throws IllegalArgumentException, UnknownHostException, JIException {
final OPCItemMgt itemManagement = group.getItemManagement();
final List<OPCITEMDEF> items = new ArrayList<OPCITEMDEF>(itemIDs.length);
for (final String id : itemIDs) {
final OPCITEMDEF item = new OPCITEMDEF();
item.setItemID(id);
item.setClientHandle(new Random().nextInt());
items.add(item);
}
final OPCITEMDEF[] itemArray = items.toArray(new OPCITEMDEF[0]);
System.out.println("Validate");
KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result = itemManagement
.validate(itemArray);
if (!dumpOPCITEMRESULT(result)) {
return;
}
// now add them to the group
System.out.println("Add");
result = itemManagement.add(itemArray);
if (!dumpOPCITEMRESULT(result)) {
return;
}
// get the server handle array
final Integer[] serverHandles = new Integer[itemArray.length];
for (int i = 0; i < itemArray.length; i++) {
serverHandles[i] = new Integer(result.get(i).getValue()
.getServerHandle());
}
// set them active
System.out.println("Activate");
final ResultSet<Integer> resultSet = itemManagement.setActiveState(
true, serverHandles);
for (final Result<Integer> resultEntry : resultSet) {
System.out.println(String.format("Item: %08X, Error: %08X",
resultEntry.getValue(), resultEntry.getErrorCode()));
}
// set client handles
System.out.println("Set client handles");
final Integer[] clientHandles = new Integer[serverHandles.length];
for (int i = 0; i < serverHandles.length; i++) {
clientHandles[i] = i;
}
itemManagement.setClientHandles(serverHandles, clientHandles);
System.out.println("Create async IO 2.0 object");
final OPCAsyncIO2 asyncIO2 = group.getAsyncIO2();
// connect handler
System.out.println("attach");
final EventHandler eventHandler = group.attach(new DumpDataCallback());
System.out.println("attach..enable");
asyncIO2.setEnable(true);
System.out.println("attach..refresh");
final int cancelId = asyncIO2.refresh(OPCDATASOURCE.OPC_DS_DEVICE, 1);
System.out.println("Cancel ID: " + cancelId);
System.out.println("attach..read");
final AsyncResult asyncResult = asyncIO2.read(2, serverHandles);
System.out.println(String.format("attach..read..cancelId: %08X",
asyncResult.getCancelId()));
// sleep
try {
System.out.println("Waiting...");
Thread.sleep(10 * 1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.out.println("Detaching");
eventHandler.detach();
// set them inactive
System.out.println("In-Active");
itemManagement.setActiveState(false, serverHandles);
// finally remove them again
System.out.println("Remove");
itemManagement.remove(serverHandles);
}
public static void showError(final OPCCommon common, final int errorCode)
throws JIException {
System.out.println(String.format("Error (%X): '%s'", errorCode,
common.getErrorString(errorCode, 1033)));
}
public static void showError(final OPCServer server, final int errorCode)
throws JIException {
showError(server.getCommon(), errorCode);
}
public static boolean dumpOPCITEMRESULT(
final KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result) {
int failed = 0;
for (final KeyedResult<OPCITEMDEF, OPCITEMRESULT> resultEntry : result) {
System.out.println("==================================");
System.out.println(String.format("Item: '%s' ", resultEntry
.getKey().getItemID()));
System.out.println(String.format("Error Code: %08x",
resultEntry.getErrorCode()));
if (!resultEntry.isFailed()) {
System.out.println(String.format("Server Handle: %08X",
resultEntry.getValue().getServerHandle()));
System.out.println(String.format("Data Type: %d", resultEntry
.getValue().getCanonicalDataType()));
System.out.println(String.format("Access Rights: %d",
resultEntry.getValue().getAccessRights()));
System.out.println(String.format("Reserved: %d", resultEntry
.getValue().getReserved()));
} else {
failed++;
}
}
return failed == 0;
}
}

View File

@ -0,0 +1,60 @@
package com.freud.dcom.utgard.cases;
import org.openscada.opc.dcom.common.KeyedResult;
import org.openscada.opc.dcom.common.KeyedResultSet;
import org.openscada.opc.dcom.common.ResultSet;
import org.openscada.opc.dcom.da.IOPCDataCallback;
import org.openscada.opc.dcom.da.ValueData;
public class DumpDataCallback implements IOPCDataCallback {
public void cancelComplete(final int transactionId,
final int serverGroupHandle) {
System.out.println(String.format("cancelComplete: %08X, Group: %08X",
transactionId, serverGroupHandle));
}
public void dataChange(final int transactionId,
final int serverGroupHandle, final int masterQuality,
final int masterErrorCode,
final KeyedResultSet<Integer, ValueData> result) {
System.out.println(String.format(
"dataChange: %d, Group: %08X, MasterQ: %d, Error: %d",
transactionId, serverGroupHandle, masterQuality,
masterErrorCode));
for (final KeyedResult<Integer, ValueData> entry : result) {
System.out.println(String.format(
"%08X - Error: %08X, Quality: %d, %Tc - %s",
entry.getKey(), entry.getErrorCode(), entry.getValue()
.getQuality(), entry.getValue().getTimestamp(),
entry.getValue().getValue().toString()));
}
}
public void readComplete(final int transactionId,
final int serverGroupHandle, final int masterQuality,
final int masterErrorCode,
final KeyedResultSet<Integer, ValueData> result) {
System.out.println(String.format(
"readComplete: %d, Group: %08X, MasterQ: %d, Error: %d",
transactionId, serverGroupHandle, masterQuality,
masterErrorCode));
for (final KeyedResult<Integer, ValueData> entry : result) {
System.out.println(String.format(
"%08X - Error: %08X, Quality: %d, %Tc - %s",
entry.getKey(), entry.getErrorCode(), entry.getValue()
.getQuality(), entry.getValue().getTimestamp(),
entry.getValue().getValue().toString()));
}
}
public void writeComplete(final int transactionId,
final int serverGroupHandle, final int masterErrorCode,
final ResultSet<Integer> result) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,85 @@
package com.freud.opc.utgard;
import java.io.IOException;
import java.util.Properties;
import org.openscada.opc.lib.common.ConnectionInformation;
/**
* 配置文件工具类
*
* @author Freud
*
*/
public final class BaseConfiguration {
private final static ConnectionInformation ci;
private final static Properties prop;
public final static String CONFIG_USERNAME = "username";
public final static String CONFIG_PASSWORD = "password";
public final static String CONFIG_HOST = "host";
public final static String CONFIG_DOMAIN = "domain";
public final static String CONFIG_CLSID = "clsid";
public final static String CONFIG_PROGID = "progid";
private final static String CONFIG_FILE_NAME = "config.properties";
/**
* 加载配置文件
*/
static {
ci = new ConnectionInformation();
prop = new Properties();
try {
prop.load(BaseConfiguration.class.getClassLoader()
.getResourceAsStream(CONFIG_FILE_NAME));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 通过名字获得配置的值
*
* @param name
* @return
*/
public static String getEntryValue(String name) {
return prop.getProperty(name);
}
/**
* 获得包含ClsId的连接信息
*
* @return
*/
public static ConnectionInformation getCLSIDConnectionInfomation() {
ci.setProgId(null);
getConnectionInfomation();
ci.setClsid(prop.getProperty(CONFIG_CLSID));
return ci;
}
/**
* 获得包含ProgId的连接信息
*
* @return
*/
public static ConnectionInformation getPROGIDConnectionInfomation() {
ci.setClsid(null);
getConnectionInfomation();
ci.setProgId(prop.getProperty(CONFIG_PROGID));
return ci;
}
/**
* 获得基础的连接信息
*/
private static void getConnectionInfomation() {
ci.setHost(prop.getProperty(CONFIG_HOST));
ci.setDomain(prop.getProperty(CONFIG_DOMAIN));
ci.setUser(prop.getProperty(CONFIG_USERNAME));
ci.setPassword(prop.getProperty(CONFIG_PASSWORD));
}
}

View File

@ -0,0 +1,50 @@
package com.freud.opc.utgard.cases;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;
import java.util.Collection;
import org.openscada.opc.dcom.list.ClassDetails;
import org.openscada.opc.lib.list.Categories;
import org.openscada.opc.lib.list.Category;
import org.openscada.opc.lib.list.ServerList;
/**
* 获得Server上所有的OPC连接信息
*
* @author Freud
*
*/
public class OPCTest1 {
public static void main(String[] args) throws Exception {
ServerList serverList = new ServerList(getEntryValue(CONFIG_HOST),
getEntryValue(CONFIG_USERNAME), getEntryValue(CONFIG_PASSWORD),
getEntryValue(CONFIG_DOMAIN));
/** 通过ProgId获得ClsId然后获得ClassDetai */
// final String cls = serverList
// .getClsIdFromProgId("Matrikon.OPC.Simulation.1");
//
// ClassDetails cd = serverList.getDetails(cls);
//
// if (cd != null) {
// System.out.println(cd.getProgId() + "=" + cd.getDescription());
// }
Collection<ClassDetails> classDetails = serverList
.listServersWithDetails(new Category[] {
Categories.OPCDAServer10, Categories.OPCDAServer20,
Categories.OPCDAServer30 }, new Category[] {});
for (ClassDetails cds : classDetails) {
System.out.println(cds.getProgId() + "=" + cds.getDescription());
}
}
}

View File

@ -0,0 +1,96 @@
package com.freud.opc.utgard.cases;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.browser.Branch;
import org.openscada.opc.lib.da.browser.FlatBrowser;
import org.openscada.opc.lib.da.browser.Leaf;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 通过ClsId定位到连接并将连接下的所有Group和Item打印
*
* @author Freud
*
*/
public class OPCTest2 {
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
/** 获得OPC连接下所有的Group和Item */
dumpTree(server.getTreeBrowser().browse(), 0);
/** 获得OPC下所有的Item */
dumpFlat(server.getFlatBrowser());
server.disconnect();
}
/**
* 遍历Flat结构的所有Item值
*
* @param browser
* @throws IllegalArgumentException
* @throws UnknownHostException
* @throws JIException
*/
private static void dumpFlat(final FlatBrowser browser)
throws IllegalArgumentException, UnknownHostException, JIException {
for (String name : browser.browse()) {
System.out.println(name);
}
}
/**
* 遍历Tree结构
*
* @param branch
* @param level
*/
private static void dumpTree(final Branch branch, final int level) {
for (final Leaf leaf : branch.getLeaves()) {
dumpLeaf(leaf, level);
}
for (final Branch subBranch : branch.getBranches()) {
dumpBranch(subBranch, level);
dumpTree(subBranch, level + 1);
}
}
private static String printTab(int level) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < level; i++) {
sb.append("\t");
}
return sb.toString();
}
/**
* 打印Item
*
* @param leaf
*/
private static void dumpLeaf(final Leaf leaf, final int level) {
System.out.println(printTab(level) + "Leaf: " + leaf.getName() + ":"
+ leaf.getItemId());
}
/**
* 打印Group
*
* @param branch
*/
private static void dumpBranch(final Branch branch, final int level) {
System.out.println(printTab(level) + "Branch: " + branch.getName());
}
}

View File

@ -0,0 +1,51 @@
package com.freud.opc.utgard.cases;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.Server;
import com.freud.opc.utgard.BaseConfiguration;
/**
* ͬ²½Áȡij¸öµãλµÄÖµ
*
* @author Freud
*
*/
public class OPCTest3 {
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
Group group = server.addGroup();
Item item = group.addItem("Random.Real5");
Map<String, Item> items = group.addItems("Random.Real1",
"Random.Real2", "Random.Real3", "Random.Real4");
dumpItem(item);
for (Entry<String, Item> temp : items.entrySet()) {
dumpItem(temp.getValue());
}
server.dispose();
}
private static void dumpItem(Item item) throws JIException {
System.out.println("[" + (++count) + "],ItemName:[" + item.getId()
+ "],value:" + item.read(false).getValue());
}
private static int count;
}

View File

@ -0,0 +1,64 @@
package com.freud.opc.utgard.cases;
import java.util.concurrent.Executors;
import org.openscada.opc.lib.da.AccessBase;
import org.openscada.opc.lib.da.DataCallback;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.SyncAccess;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 同步Access读取某个点的变化值
*
* @author Freud
*
*/
public class OPCTest4 {
/** 间隔时间 */
private static final int PERIOD = 100;
/** 休眠时间 */
private static final int SLEEP = 2000;
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
/**
* 其中100单位为毫秒为每次从OPC获取刷新的间隔时间
*/
AccessBase access = new SyncAccess(server, PERIOD);
/**
* 定时每隔间隔时间获取一次值
*/
access.addItem("Random.Real5", new DataCallback() {
private int i;
@Override
public void changed(Item item, ItemState itemstate) {
System.out.println("[" + (++i) + "],ItemName:[" + item.getId()
+ "],value:" + itemstate.getValue());
}
});
/** 开始监听 */
access.bind();
/** 当前线程休眠时间单位:毫秒 */
Thread.sleep(SLEEP);
/** 监听 结束 */
access.unbind();
server.dispose();
}
}

View File

@ -0,0 +1,65 @@
package com.freud.opc.utgard.cases;
import java.util.concurrent.Executors;
import org.openscada.opc.lib.da.AccessBase;
import org.openscada.opc.lib.da.Async20Access;
import org.openscada.opc.lib.da.DataCallback;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 异步Access订阅读取点位的值,并且只有值有变化的时候才会触发CallBack函数
*
* @author Freud
*
*/
public class OPCTest5 {
/** 间隔时间 */
private static final int PERIOD = 100;
/** 休眠时间 */
private static final int SLEEP = 2000;
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
/**
* 其中100单位为毫秒为每次从OPC获取刷新的间隔时间
*/
AccessBase access = new Async20Access(server, PERIOD, false);
/**
* 只有Item的值有变化的时候才会触发CallBack函数
*/
access.addItem("Random.Real5", new DataCallback() {
private int count;
@Override
public void changed(Item item, ItemState itemstate) {
System.out.println("[" + (++count) + "],ItemName:["
+ item.getId() + "],value:" + itemstate.getValue());
}
});
/** 开始监听 */
access.bind();
/** 当前线程休眠时间单位:毫秒 */
Thread.sleep(SLEEP);
/** 监听 结束 */
access.unbind();
server.dispose();
}
}

View File

@ -0,0 +1,68 @@
package com.freud.opc.utgard.cases;
import java.util.concurrent.Executors;
import org.openscada.opc.lib.da.AccessBase;
import org.openscada.opc.lib.da.AutoReconnectController;
import org.openscada.opc.lib.da.DataCallback;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ItemState;
import org.openscada.opc.lib.da.Server;
import org.openscada.opc.lib.da.SyncAccess;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 如果Connection Break掉了会自动重新连接
*
* @author Freud
*
*/
public class OPCTest6 {
/** 间隔时间 */
private static final int PERIOD = 100;
/** 休眠时间 */
private static final int SLEEP = 2000;
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
AutoReconnectController controller = new AutoReconnectController(server);
controller.connect();
/**
* 其中100单位为毫秒为每次从OPC获取刷新的间隔时间
*/
AccessBase access = new SyncAccess(server, PERIOD);
/**
* 定时每隔间隔时间获取一次值
*/
access.addItem("Random.Real5", new DataCallback() {
private int i;
@Override
public void changed(Item item, ItemState itemstate) {
System.out.println("[" + (++i) + "],ItemName:[" + item.getId()
+ "],value:" + itemstate.getValue());
}
});
/** 开始监听 */
access.bind();
/** 当前线程休眠时间单位:毫秒 */
Thread.sleep(SLEEP);
/** 监听结束 */
access.unbind();
controller.disconnect();
}
}

View File

@ -0,0 +1,55 @@
package com.freud.opc.utgard.cases;
import java.util.concurrent.Executors;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.Server;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 同步写入某个点位的值
*
* @author Freud
*
*/
public class OPCTest7 {
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
Group group = server.addGroup();
Item item = group.addItem("Square Waves.Real4");
/** 构造写入数据 */
final Float[] integerData = new Float[] { 1202f, 1203f, 1204f };
final JIArray array = new JIArray(integerData, false);
final JIVariant value = new JIVariant(array);
/** 同步写入 */
item.write(value);
Thread.sleep(1000);
/** Dump出item的值 */
dumpItem(item);
server.dispose();
}
private static void dumpItem(Item item) throws JIException {
System.out.println("[" + (++count) + "],ItemName:[" + item.getId()
+ "],value:" + item.read(true).getValue());
}
private static int count;
}

View File

@ -0,0 +1,54 @@
package com.freud.opc.utgard.cases;
import java.util.concurrent.Executors;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.Server;
import com.freud.opc.utgard.BaseConfiguration;
/**
* 异步写入
*
* @author Freud
*
*/
public class OPCTest8 {
public static void main(String[] args) throws Exception {
Server server = new Server(
BaseConfiguration.getCLSIDConnectionInfomation(),
Executors.newSingleThreadScheduledExecutor());
server.connect();
Group group = server.addGroup();
Item item = group.addItem("Square Waves.Real4");
/** 构造写入数据 */
final Float[] integerData = new Float[] { 1202f, 1203f, 1204f };
final JIArray array = new JIArray(integerData, false);
final JIVariant value = new JIVariant(array);
/** 同步写入 */
item.write(value);
Thread.sleep(1000);
/** Dump出item的值 */
dumpItem(item);
server.dispose();
}
private static void dumpItem(Item item) throws JIException {
System.out.println("[" + (++count) + "],ItemName:[" + item.getId()
+ "],value:" + item.read(true).getValue());
}
private static int count;
}

View File

@ -0,0 +1,6 @@
host=10.1.5.123
domain=
username=neusoft
password=`1nktd84jx
clsid=F8582CF2-88FB-11D0-B850-00C0F0104305
progid=

View File

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %c.%M:%L - %m%n" />
</layout>
</appender>
<appender name="FILE_OUT" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="output.log" /><!-- 设置日志输出文件名 -->
<!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->
<param name="Append" value="false" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p %c.%M:%L - %m%n" />
</layout>
</appender>
<!-- specify the logging level for loggers from other libraries -->
<logger name="com.freud.dcom.utgard.cases.*" additivity="false">
<priority value="info"/>
<appender-ref ref="FILE_OUT" />
</logger>
<!-- for all other loggers log only info and above log messages -->
<root>
<priority value="INFO" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_OUT" />
</root>
</log4j:configuration>