Search in sources :

Example 1 with AnonymousProvider

use of org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider in project netxms by netxms.

the class ServerConnection method connect.

/**
 * Connect to server
 *
 * @throws Exception on any error
 */
private void connect() throws Exception {
    if (session != null)
        return;
    try {
        session = OpcUaClient.create(url, endpoints -> endpoints.stream().filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())).findFirst(), configBuilder -> configBuilder.setApplicationName(LocalizedText.english("NetXMS Agent")).setApplicationUri("urn:netxms:agent").setIdentityProvider(new AnonymousProvider()).setRequestTimeout(UInteger.valueOf(5000)).build());
        session.connect().get(timeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        Platform.writeDebugLog(5, String.format("OPCUA: cannot setup connection to %s (%s)", url, e.getMessage()));
        Platform.writeDebugLog(5, "OPCUA:   ", e);
        throw e;
    }
}
Also used : StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) Platform(org.netxms.bridge.Platform) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) ExpandedNodeId(org.eclipse.milo.opcua.stack.core.types.builtin.ExpandedNodeId) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) LocalizedText(org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Variant(org.eclipse.milo.opcua.stack.core.types.builtin.Variant) ImmutableList(com.google.common.collect.ImmutableList) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) Map(java.util.Map) UaVariableNode(org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) UaRuntimeException(org.eclipse.milo.opcua.stack.core.UaRuntimeException) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with AnonymousProvider

use of org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider in project milo by eclipse.

the class OpcUaClientConfigTest method testCopy.

@Test
public void testCopy() {
    OpcUaClientConfig original = OpcUaClientConfig.builder().setEndpoint(endpoint).setSessionName(() -> "testSessionName").setSessionTimeout(uint(60000 * 60)).setRequestTimeout(uint(120000)).setMaxResponseMessageSize(UInteger.MAX).setMaxPendingPublishRequests(uint(2)).setIdentityProvider(new AnonymousProvider()).setSessionLocaleIds(new String[] { "en", "es" }).build();
    OpcUaClientConfig copy = OpcUaClientConfig.copy(original).build();
    assertEquals(copy.getSessionName(), original.getSessionName());
    assertEquals(copy.getSessionTimeout(), original.getSessionTimeout());
    assertEquals(copy.getRequestTimeout(), original.getRequestTimeout());
    assertEquals(copy.getMaxResponseMessageSize(), original.getMaxResponseMessageSize());
    assertEquals(copy.getMaxPendingPublishRequests(), original.getMaxPendingPublishRequests());
    assertEquals(copy.getIdentityProvider(), original.getIdentityProvider());
    assertEquals(copy.getKeepAliveFailuresAllowed(), original.getKeepAliveFailuresAllowed());
    assertEquals(copy.getKeepAliveInterval(), original.getKeepAliveInterval());
    assertEquals(copy.getKeepAliveTimeout(), original.getKeepAliveTimeout());
    assertEquals(copy.getSessionLocaleIds(), original.getSessionLocaleIds());
}
Also used : AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) Test(org.testng.annotations.Test)

Example 3 with AnonymousProvider

use of org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider in project milo by eclipse.

the class OpcUaClientConfigTest method testCopyAndModify.

@Test
public void testCopyAndModify() {
    OpcUaClientConfig original = OpcUaClientConfig.builder().setEndpoint(endpoint).setSessionName(() -> "testSessionName").setSessionTimeout(uint(60000 * 60)).setRequestTimeout(uint(120000)).setMaxResponseMessageSize(UInteger.MAX).setMaxPendingPublishRequests(uint(2)).setIdentityProvider(new AnonymousProvider()).build();
    OpcUaClientConfig copy = OpcUaClientConfig.copy(original, builder -> builder.setSessionName(() -> "foo").setSessionTimeout(uint(0)).setRequestTimeout(uint(0)).setMaxResponseMessageSize(uint(0)).setMaxPendingPublishRequests(uint(0)).setIdentityProvider(new AnonymousProvider()).setKeepAliveFailuresAllowed(uint(2)).setKeepAliveInterval(uint(10000)).setKeepAliveTimeout(uint(15000)).setSessionLocaleIds(new String[] { "en", "es" }));
    assertNotEquals(copy.getSessionName(), original.getSessionName());
    assertNotEquals(copy.getIdentityProvider(), original.getIdentityProvider());
    assertNotEquals(copy.getSessionLocaleIds(), original.getSessionLocaleIds());
    assertEquals(copy.getSessionTimeout(), uint(0));
    assertEquals(copy.getRequestTimeout(), uint(0));
    assertEquals(copy.getMaxResponseMessageSize(), uint(0));
    assertEquals(copy.getMaxPendingPublishRequests(), uint(0));
    assertEquals(copy.getKeepAliveFailuresAllowed(), uint(2));
    assertEquals(copy.getKeepAliveInterval(), uint(10000));
    assertEquals(copy.getKeepAliveTimeout(), uint(15000));
    assertEquals(copy.getSessionLocaleIds(), new String[] { "en", "es" });
}
Also used : AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) Test(org.testng.annotations.Test)

Example 4 with AnonymousProvider

use of org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider in project JBM by numen06.

the class OpcUaTemplate method getOpcUaClient.

/**
 * Get Opc Ua Client
 *
 * @param deviceId   Device Id
 * @param driverInfo Driver Info
 * @return OpcUaClient
 * @throws UaException UaException
 */
public OpcUaClient getOpcUaClient(String deviceId, OpcUaSource driverInfo) {
    OpcUaClient opcUaClient = null;
    if (clientMap.containsKey(deviceId))
        return clientMap.get(deviceId).getOpcUaClient();
    try {
        KeyLoader loader = new KeyLoader().load(Paths.get(FileUtil.getTmpDirPath()));
        if (null == opcUaClient) {
            try {
                List<EndpointDescription> remoteEndpoints = DiscoveryClient.getEndpoints(driverInfo.getUrl()).get();
                EndpointDescription configPoint = EndpointUtil.updateUrl(remoteEndpoints.get(0), driverInfo.getHost(), driverInfo.getPort());
                opcUaClient = OpcUaClient.create(driverInfo.getUrl(), endpoints -> remoteEndpoints.stream().findFirst(), configBuilder -> configBuilder.setIdentityProvider(new AnonymousProvider()).setCertificate(loader.getClientCertificate()).setKeepAliveInterval(uint(3000)).setRequestTimeout(uint(5000)).setEndpoint(configPoint).build());
            // clientMap.put(deviceId, new OpcUaClientBean(deviceId, opcUaClient));
            } catch (UaException e) {
                log.error("get opc ua client error: {}", e.getMessage());
            // clientMap.entrySet().removeIf(next -> next.getKey().equals(deviceId));
            }
        }
    } catch (Exception e) {
        log.error("get opc ua client error: {}", e.getMessage());
    }
    // return clientMap.get(deviceId).getOpcUaClient();
    return opcUaClient;
}
Also used : MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) PointSubscribeEvent(com.jbm.framework.opcua.event.PointSubscribeEvent) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) Autowired(org.springframework.beans.factory.annotation.Autowired) ValueChanageEvent(com.jbm.framework.opcua.event.ValueChanageEvent) CompletableFuture(java.util.concurrent.CompletableFuture) Lists(com.google.common.collect.Lists) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Service(org.springframework.stereotype.Service) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) Map(java.util.Map) UaMonitoredItem(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem) org.eclipse.milo.opcua.stack.core.types.builtin(org.eclipse.milo.opcua.stack.core.types.builtin) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) GuardSubscriptionListener(com.jbm.framework.opcua.listener.GuardSubscriptionListener) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) SessionActivityListener(org.eclipse.milo.opcua.sdk.client.SessionActivityListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Maps(com.google.common.collect.Maps) ApplicationContext(org.springframework.context.ApplicationContext) KeyLoader(com.jbm.framework.opcua.key.KeyLoader) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CollUtil(cn.hutool.core.collection.CollUtil) StrUtil(cn.hutool.core.util.StrUtil) Slf4j(lombok.extern.slf4j.Slf4j) org.eclipse.milo.opcua.stack.core.types.structured(org.eclipse.milo.opcua.stack.core.types.structured) List(java.util.List) JSON(com.alibaba.fastjson.JSON) OpcPointsRead(com.jbm.framework.opcua.attribute.OpcPointsRead) Paths(java.nio.file.Paths) ReflectUtil(cn.hutool.core.util.ReflectUtil) UaException(org.eclipse.milo.opcua.stack.core.UaException) DiscoveryClient(org.eclipse.milo.opcua.stack.client.DiscoveryClient) FileUtil(cn.hutool.core.io.FileUtil) ValueType(com.jbm.framework.opcua.attribute.ValueType) DriverUtils(com.jbm.framework.opcua.util.DriverUtils) OpcPoint(com.jbm.framework.opcua.attribute.OpcPoint) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) UaException(org.eclipse.milo.opcua.stack.core.UaException) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) KeyLoader(com.jbm.framework.opcua.key.KeyLoader) ExecutionException(java.util.concurrent.ExecutionException) UaException(org.eclipse.milo.opcua.stack.core.UaException)

Example 5 with AnonymousProvider

use of org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider in project OpenMUC by isc-konstanz.

the class OpcConnection method connect.

@Connect
public void connect() throws ConnectionException {
    try {
        Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
        Files.createDirectories(securityTempDir);
        if (!Files.exists(securityTempDir)) {
            throw new ConnectionException("Unable to create security dir: " + securityTempDir);
        }
        logger.debug("Security temp dir: {}", securityTempDir.toAbsolutePath());
        KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
        if (!address.contains("opc.tcp://")) {
            host = address.split(":")[0];
            port = Integer.parseInt(address.split(":")[1]);
            address = "opc.tcp://" + address;
        } else {
            host = address.split("//|:")[1];
            port = Integer.parseInt(address.split("//|:")[2]);
        }
        List<EndpointDescription> endpoints = DiscoveryClient.getEndpoints(address).get();
        EndpointDescription endpoint = endpoints.stream().filter(e -> true).findFirst().orElseThrow(() -> new UaException(StatusCodes.Bad_ConfigurationError, "No endpoint selected"));
        logger.info("OPC Client connecting to {}.", address);
        endpoint = EndpointUtil.updateUrl(endpoints.get(0), host, port);
        OpcUaClientConfigBuilder clientBuilder = new OpcUaClientConfigBuilder().setEndpoint(endpoint).setApplicationName(LocalizedText.english("OpenMUC OPC UA Client")).setApplicationUri("urn:openmuc:client").setCertificate(loader.getClientCertificate()).setKeyPair(loader.getClientKeyPair()).setIdentityProvider(new AnonymousProvider()).setRequestTimeout(uint(5000));
        client = OpcUaClient.create(clientBuilder.build());
        client.connect().get();
        // Get a typed reference to the Server object: ServerNode
        ServerTypeNode serverNode = client.getAddressSpace().getObjectNode(Identifiers.Server, ServerTypeNode.class).get();
        if (namespaceUri != null && !namespaceUri.isEmpty()) {
            try {
                namespaceIndex = Integer.parseInt(namespaceUri);
            } catch (NumberFormatException e) {
                namespaceIndex = Arrays.asList(serverNode.getNamespaceArray().get()).indexOf(namespaceUri);
            }
        }
    } catch (Exception e) {
        logger.error("OPC connection to server failed {}", e);
    }
}
Also used : Path(java.nio.file.Path) OpcUaClientConfigBuilder(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfigBuilder) ServerTypeNode(org.eclipse.milo.opcua.sdk.client.model.nodes.objects.ServerTypeNode) UaException(org.eclipse.milo.opcua.stack.core.UaException) AnonymousProvider(org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ConnectionException(org.openmuc.framework.driver.spi.ConnectionException) ConnectionException(org.openmuc.framework.driver.spi.ConnectionException) ExecutionException(java.util.concurrent.ExecutionException) UaException(org.eclipse.milo.opcua.stack.core.UaException) Connect(org.openmuc.framework.driver.annotation.Connect)

Aggregations

AnonymousProvider (org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider)6 ExecutionException (java.util.concurrent.ExecutionException)3 List (java.util.List)2 Map (java.util.Map)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 TimeUnit (java.util.concurrent.TimeUnit)2 OpcUaClient (org.eclipse.milo.opcua.sdk.client.OpcUaClient)2 OpcUaClientConfig (org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig)2 UaException (org.eclipse.milo.opcua.stack.core.UaException)2 Test (org.testng.annotations.Test)2 CollUtil (cn.hutool.core.collection.CollUtil)1 FileUtil (cn.hutool.core.io.FileUtil)1 ReflectUtil (cn.hutool.core.util.ReflectUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 JSON (com.alibaba.fastjson.JSON)1 ImmutableList (com.google.common.collect.ImmutableList)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 OpcPoint (com.jbm.framework.opcua.attribute.OpcPoint)1 OpcPointsRead (com.jbm.framework.opcua.attribute.OpcPointsRead)1