Search in sources :

Example 1 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class ManualKnxNetIp method main.

// Addresses:
// */*/10: Temperature
// */*/12: Heating
// */*/60: Primary Window
// */*/64: Second Window
// */*/101: Power Line 1
public static void main(String[] args) throws Exception {
    // final PlcConnection connection = new PlcDriverManager().getConnection("knxnet-ip://192.168.42.11?knxproj-file-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Stettiner%20Str.%2013/StettinerStr-Soll-Ist-Temperatur.knxproj");
    final PlcConnection connection = new PlcDriverManager().getConnection("knxnet-ip:pcap:///Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Recording-01.03.2020-2.pcapng?knxproj-file-path=/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/KNX/Stettiner%20Str.%2013/StettinerStr-Soll-Ist-Temperatur.knxproj");
    // Make sure we hang up correctly when terminating.
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            connection.close();
        } catch (Exception e) {
            throw new PlcRuntimeException("Error closing connection", e);
        }
    }));
    // Create a new subscription request.
    // The address and the name is just bogus as we're always returning everything.
    // We will probably refactor the API in the near future.
    final PlcSubscriptionRequest subscriptionRequest = connection.subscriptionRequestBuilder().addEventField("knxData", "*/*/*").build();
    // Register the subscription
    // The timeout is also just a bogus value as the data is coming in actively
    // We will probably refactor the API in the near future.
    final PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get(1000, TimeUnit.MILLISECONDS);
    // Register a callback which is called on new data being available.
    final PlcSubscriptionHandle subscriptionHandle = subscriptionResponse.getSubscriptionHandle("knxData");
    subscriptionHandle.register(knxData -> {
        System.out.println(knxData.getTimestamp().toString() + " - " + ((DefaultPlcSubscriptionEvent) knxData).getValues().get("knxData"));
    });
}
Also used : PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException)

Example 2 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class Main method main.

public static void main(String[] args) throws Exception {
    PlcDriverManager driverManager = new PlcDriverManager();
    CANOpenDriverContext.CALLBACK.addCallback(new Callback() {

        @Override
        public void receive(CANOpenFrame frame) {
        // System.err.println("Received frame " + frame);
        }
    });
    PlcConnection connection = driverManager.getConnection("canopen:javacan://vcan0?nodeId=11");
    // UUID.randomUUID().toString();
    String value = "abcdef";
    CompletableFuture<? extends PlcWriteResponse> response = connection.writeRequestBuilder().addItem("foo", "SDO:13:0x2000/0x0:VISIBLE_STRING", value).build().execute();
    response.whenComplete((writeReply, writeError) -> {
        System.out.println("====================================");
        if (writeError != null) {
            System.out.println("Error ");
            writeError.printStackTrace();
        } else {
            System.out.println("Result " + writeReply.getResponseCode("foo") + " " + value);
            PlcReadRequest.Builder builder = connection.readRequestBuilder();
            builder.addItem("foo", "SDO:13:0x2000/0x0:VISIBLE_STRING");
            CompletableFuture<? extends PlcReadResponse> future = builder.build().execute();
            future.whenComplete((readReply, readError) -> {
                System.out.println("====================================");
                if (readError != null) {
                    System.out.println("Error ");
                    readError.printStackTrace();
                } else {
                    System.out.println("Result " + readReply.getString("foo"));
                }
            });
        }
    });
// while (true) {
// }
}
Also used : Callback(org.apache.plc4x.java.canopen.listener.Callback) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PlcConnection(org.apache.plc4x.java.api.PlcConnection) CANOpenFrame(org.apache.plc4x.java.canopen.readwrite.CANOpenFrame)

Example 3 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class Plc4xCommunication method setValue.

public void setValue(String tag, String value, String connectionString) {
    PlcConnection connection = null;
    try {
        connection = driverManager.getConnection(connectionString);
        if (connection.isConnected() == false) {
            logger.debug("getConnection() returned a connection that isn't connected");
            connection.connect();
        }
    } catch (PlcConnectionException e) {
        logger.warn("Failed" + e);
    }
    if (!connection.getMetadata().canWrite()) {
        logger.error("This connection doesn't support writing.");
        try {
            connection.close();
        } catch (Exception e) {
            logger.warn("Closing connection failed with error " + e);
        }
        return;
    }
    // Create a new read request:
    // - Give the single item requested an alias name
    final PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
    // If an array value is passed instead of a single value then convert to a String array
    if ((value.charAt(0) == '[') && (value.charAt(value.length() - 1) == ']')) {
        String[] values = value.substring(1, value.length() - 1).split(",");
        logger.info("Adding Tag " + Arrays.toString(values));
        builder.addItem(tag, tag, values);
    } else {
        builder.addItem(tag, tag, value);
    }
    PlcWriteRequest writeRequest = builder.build();
    try {
        writeRequest.execute().get();
    } catch (InterruptedException | ExecutionException e) {
        logger.warn("Failed" + e);
    }
    try {
        connection.close();
    } catch (Exception e) {
        logger.warn("Closing Connection Failed with error " + e);
    }
    return;
}
Also used : PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException) PlcConnection(org.apache.plc4x.java.api.PlcConnection) TimeoutException(java.util.concurrent.TimeoutException) PlcConnectionException(org.apache.plc4x.java.api.exceptions.PlcConnectionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class MockDriver method getConnection.

@Override
public PlcConnection getConnection(String url) throws PlcConnectionException {
    // Mock a connection.
    PlcConnection plcConnectionMock = mock(PlcConnection.class, RETURNS_DEEP_STUBS);
    when(plcConnectionMock.getMetadata().canRead()).thenReturn(true);
    when(plcConnectionMock.getMetadata().canWrite()).thenReturn(true);
    when(plcConnectionMock.readRequestBuilder()).thenReturn(mock(PlcReadRequest.Builder.class, RETURNS_DEEP_STUBS));
    when(plcConnectionMock.writeRequestBuilder()).thenReturn(mock(PlcWriteRequest.Builder.class, RETURNS_DEEP_STUBS));
    when(plcConnectionMock.subscriptionRequestBuilder()).thenReturn(mock(PlcSubscriptionRequest.Builder.class, RETURNS_DEEP_STUBS));
    when(plcConnectionMock.unsubscriptionRequestBuilder()).thenReturn(mock(PlcUnsubscriptionRequest.Builder.class, RETURNS_DEEP_STUBS));
    // Mock a typical subscriber.
    PlcSubscriber plcSubscriber = mock(PlcSubscriber.class, RETURNS_DEEP_STUBS);
    when(plcSubscriber.subscribe(any(PlcSubscriptionRequest.class))).thenAnswer(invocation -> {
        LOGGER.info("Received {}", invocation);
        // TODO: Translate this so it actually does something ...
        /*PlcSubscriptionRequest subscriptionRequest = invocation.getArgument(0);
            List<PlcSubscriptionResponse> responseItems =
                subscriptionRequest.getFieldNames().stream().map(
                    fieldName -> subscriptionRequest.getField(fieldName)).map(field -> {
                    Consumer consumer = subscriptionRequestItem.getConsumer();
                    executorService.submit(() -> {
                        while (!Thread.currentThread().isInterrupted()) {
                            consumer.accept(new SubscriptionEventItem<>(null, Calendar.getInstance(), Collections.singletonList("HelloWorld")));
                            try {
                                TimeUnit.MILLISECONDS.sleep(100);
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    return new SubscriptionResponseItem<>(subscriptionRequestItem,
                        mock(PlcSubscriptionHandle.class, RETURNS_DEEP_STUBS), PlcResponseCode.OK);
                }).collect(Collectors.toList());
            PlcSubscriptionResponse response = new PlcSubscriptionResponse(subscriptionRequest, responseItems);*/
        PlcSubscriptionResponse response = new DefaultPlcSubscriptionResponse(mock(PlcSubscriptionRequest.class), new HashMap<>());
        CompletableFuture<PlcSubscriptionResponse> responseFuture = new CompletableFuture<>();
        responseFuture.complete(response);
        return responseFuture;
    });
    return plcConnectionMock;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) DefaultPlcSubscriptionResponse(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionResponse) DefaultPlcSubscriptionResponse(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionResponse) PlcSubscriber(org.apache.plc4x.java.spi.messages.PlcSubscriber) PlcConnection(org.apache.plc4x.java.api.PlcConnection)

Example 5 with PlcConnection

use of org.apache.plc4x.java.api.PlcConnection in project plc4x by apache.

the class Plc4XProducerTest method setUp.

@BeforeEach
public void setUp() throws Exception {
    Plc4XEndpoint endpointMock = mock(Plc4XEndpoint.class, RETURNS_DEEP_STUBS);
    when(endpointMock.getEndpointUri()).thenReturn("plc4x:mock:10.10.10.1/1/1");
    PlcConnection mockConnection = mock(PlcConnection.class, RETURNS_DEEP_STUBS);
    when(mockConnection.getMetadata().canRead()).thenReturn(true);
    when(mockConnection.getMetadata().canWrite()).thenReturn(true);
    when(mockConnection.writeRequestBuilder()).thenReturn(mock(PlcWriteRequest.Builder.class, RETURNS_DEEP_STUBS));
    when(endpointMock.getConnection()).thenReturn(mockConnection);
    SUT = new Plc4XProducer(endpointMock);
    testExchange = mock(Exchange.class, RETURNS_DEEP_STUBS);
    Map<String, Map<String, Object>> tags = new HashMap();
    tags.put("test1", Collections.singletonMap("testAddress1", 0));
    tags.put("test1", Collections.singletonMap("testAddress2", true));
    tags.put("test1", Collections.singletonMap("testAddress3", "TestString"));
    when(testExchange.getIn().getBody()).thenReturn(tags);
}
Also used : Exchange(org.apache.camel.Exchange) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) PlcConnection(org.apache.plc4x.java.api.PlcConnection) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

PlcConnection (org.apache.plc4x.java.api.PlcConnection)78 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)36 PlcConnectionException (org.apache.plc4x.java.api.exceptions.PlcConnectionException)28 PlcReadResponse (org.apache.plc4x.java.api.messages.PlcReadResponse)23 Test (org.junit.jupiter.api.Test)22 PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)19 ExecutionException (java.util.concurrent.ExecutionException)16 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)12 TimeoutException (java.util.concurrent.TimeoutException)9 BigInteger (java.math.BigInteger)8 PlcSubscriptionResponse (org.apache.plc4x.java.api.messages.PlcSubscriptionResponse)8 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)8 Map (java.util.Map)7 MockConnection (org.apache.plc4x.java.mock.connection.MockConnection)6 HashMap (java.util.HashMap)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 Condition (org.assertj.core.api.Condition)5 Disabled (org.junit.jupiter.api.Disabled)5 Field (java.lang.reflect.Field)4 LocalDateTime (java.time.LocalDateTime)4