Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[milo-dev] Milo does not read

Hello milo-dev

I write a client which communicate with Siemens server. The Siemens parts are "old", it communicates with CPU 317-2DP over ethernet. My program reads the value but no writing is possible. Can someone help me.

Best regardes

Eckhard Gerking

/*
 * Created on 20.08.2020 from Gerking
 */
/**
 * 
 */
package de.egerking.fw.itemflowcontrol.device.opc;

import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;
import static org.junit.Assert.assertNotEquals;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.sdk.client.api.nodes.VariableNode;
import org.eclipse.milo.opcua.stack.client.DiscoveryClient;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;

import junit.framework.TestCase;

/**
 * The class <code>FB100Test</code>
 * 
 * @author Gerking
 * @since 20.08.2020
 */
public class DB300Test extends TestCase {

	/**	 */
	private final Logger logger = LogManager.getLogger(getClass());

	/**	 */
	private OpcUaClient client = null;

	/**
	 * Create the test case
	 *
	 * @param testName name of the test case
	 */
	public DB300Test(String testName) {
		super(testName);
	}

	/**
	 * 
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public void testReadWriteDB300DW334() throws InterruptedException, ExecutionException {
		logger.info("testReadWriteDB300DW334");

		NodeId nodeId = new NodeId(3, "BethLP.db300.334,B,28");

		VariableNode variableNode = getClient().getAddressSpace().createVariableNode(nodeId);

		// read the existing value
		DataValue valueBefore = variableNode.readValue().get();
		assertNotNull(valueBefore);
		logger.info("value    read " + valueBefore);

		// write a new random value
		// DataValue newValue = new DataValue(new Variant(UByte.valueOf(new
		// Random().nextInt() & 0xFF)), StatusCode.GOOD,
		// null, null);
		DataValue newValue = valueBefore;
		
		StatusCode writeStatus = variableNode.writeValue(newValue).get();
		assertTrue(writeStatus.isGood());
		logger.info("value written " + newValue);

		// read the value again
		DataValue valueAfter = variableNode.readValue().get();
		assertNotNull(valueAfter);
		logger.info("value    read " + valueAfter);

		//assertNotEquals(valueBefore, valueAfter);
		logger.info("bye");

	}

	/**
	 * Sets up the fixture.
	 */
	@Override
	protected void setUp() throws Exception {
		logger.info("setUp()");
		startClient();
	}

	/**
	 * Tears down the fixture.
	 */
	@Override
	protected void tearDown() throws Exception {
		logger.info("tearDown()");
		stopClient();
	}

	/**
	 * 
	 * @throws Exception
	 */
	protected void startClient() throws Exception {
		String endpointUrl = "opc.tcp://localhost:4845";

		Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
		Files.createDirectories(securityTempDir);
		if (!Files.exists(securityTempDir)) {
			throw new Exception("unable to create security dir: " + securityTempDir);
		}
		LogManager.getLogger(getClass()).info("security temp dir: {}", securityTempDir.toAbsolutePath());

		KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);

		SecurityPolicy securityPolicy = SecurityPolicy.None; // clientExample.getSecurityPolicy();

		List<EndpointDescription> endpoints;

		try {
			endpoints = DiscoveryClient.getEndpoints(endpointUrl).get();
		} catch (Throwable ex) {
			// try the explicit discovery endpoint as well
			String discoveryUrl = endpointUrl;

			if (!discoveryUrl.endsWith("/")) {
				discoveryUrl += "/";
			}
			discoveryUrl += "discovery";

			logger.info("Trying explicit discovery URL: {}", discoveryUrl);
			endpoints = DiscoveryClient.getEndpoints(discoveryUrl).get();
		}

		EndpointDescription endpoint = endpoints.stream()
				.filter(e -> e.getSecurityPolicyUri().equals(securityPolicy.getUri())) //
				.filter(e -> true) // clientExample.endpointFilter())
				.findFirst() //
				.orElseThrow(() -> new Exception("no desired endpoints returned"));

		logger.info("Using endpoint: {} [{}/{}]", endpoint.getEndpointUrl(), securityPolicy,
				endpoint.getSecurityMode());

		OpcUaClientConfig config = OpcUaClientConfig.builder() //
				.setApplicationName(LocalizedText.english("eclipse milo opc-ua client")) //
				.setApplicationUri("urn:eclipse:milo:examples:client") //
				.setCertificate(loader.getClientCertificate()) //
				.setKeyPair(loader.getClientKeyPair()) //
				.setEndpoint(endpoint) //
				.setIdentityProvider(new AnonymousProvider()) //
				.setRequestTimeout(uint(5000)) //
				.build();

		client = OpcUaClient.create(config);
		client.connect().get();
	}

	/**
	 * 
	 */
	protected void stopClient() {
		try {
			client.disconnect().get();
		} catch (InterruptedException | ExecutionException e) {
			logger.warn("Error disconnecting client.", e);
		}
	}

	/**
	 * 
	 */
	protected OpcUaClient getClient() {
		return client;
	}

}

Back to the top