Search in sources :

Example 1 with DefaultPlcSubscriptionEvent

use of org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent in project plc4x by apache.

the class HelloInflux method run.

public void run() {
    InfluxDBClient dbConnection = connectToDb();
    WriteApi writeApi = dbConnection.getWriteApi();
    try {
        PlcConnection plcConnection = connectToPlc();
        final PlcSubscriptionRequest subscriptionRequest = plcConnection.subscriptionRequestBuilder().addChangeOfStateField("query", configuration.getString("plc.query")).build();
        final PlcSubscriptionResponse subscriptionResponse = subscriptionRequest.execute().get(10, TimeUnit.SECONDS);
        subscriptionResponse.getSubscriptionHandle("query").register(plcSubscriptionEvent -> {
            DefaultPlcSubscriptionEvent internalEvent = (DefaultPlcSubscriptionEvent) plcSubscriptionEvent;
            final Point point = Point.measurement(configuration.getString("influx.measurement")).time(plcSubscriptionEvent.getTimestamp().toEpochMilli(), WritePrecision.MS);
            final Map<String, ResponseItem<PlcValue>> values = internalEvent.getValues();
            values.forEach((fieldName, fieldResponsePair) -> {
                final PlcResponseCode responseCode = fieldResponsePair.getCode();
                final PlcValue plcValue = fieldResponsePair.getValue();
                if (responseCode == PlcResponseCode.OK) {
                    PlcStruct structValue = (PlcStruct) plcValue;
                    for (String key : structValue.getKeys()) {
                        PlcValue subValue = structValue.getValue(key);
                        registerFields(point, key, subValue);
                    }
                }
            });
            writeApi.writePoint(configuration.getString("influx.bucket"), configuration.getString("influx.org"), point);
        });
    } catch (PlcException e) {
        logger.error("PLC Error", e);
    } catch (Exception e) {
        logger.error("General Error", e);
    }
}
Also used : InfluxDBClient(com.influxdb.client.InfluxDBClient) PlcSubscriptionRequest(org.apache.plc4x.java.api.messages.PlcSubscriptionRequest) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) Point(com.influxdb.client.write.Point) PlcConnection(org.apache.plc4x.java.api.PlcConnection) ConfigurationException(org.apache.commons.configuration2.ex.ConfigurationException) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) PlcRuntimeException(org.apache.plc4x.java.api.exceptions.PlcRuntimeException) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) PlcException(org.apache.plc4x.java.api.exceptions.PlcException) WriteApi(com.influxdb.client.WriteApi) PlcSubscriptionResponse(org.apache.plc4x.java.api.messages.PlcSubscriptionResponse) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem)

Example 2 with DefaultPlcSubscriptionEvent

use of org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent in project plc4x by apache.

the class WaterTankService method connectToFakeDevice.

protected void connectToFakeDevice() {
    WaterLevelHandler handler = new WaterLevelHandler();
    Thread thread = new Thread(() -> {
        try {
            while (true) {
                TimeUnit.MILLISECONDS.sleep(100);
                short value = (short) random.nextInt(1024);
                Map<String, ResponseItem<PlcValue>> values = new HashMap<>();
                values.put(WATER_LEVEL, new ResponseItem<>(PlcResponseCode.OK, new PlcINT(value)));
                DefaultPlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), values);
                handler.accept(event);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    });
    thread.start();
}
Also used : HashMap(java.util.HashMap) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) PlcINT(org.apache.plc4x.java.spi.values.PlcINT)

Example 3 with DefaultPlcSubscriptionEvent

use of org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent in project plc4x by apache.

the class OpcuaSubscriptionHandle method onSubscriptionValue.

/**
 * Receive the returned values from the OPCUA server and format it so that it can be received by the PLC4X client.
 *
 * @param values - array of data values to be sent to the client.
 */
private void onSubscriptionValue(MonitoredItemNotification[] values) {
    LinkedHashSet<String> fieldList = new LinkedHashSet<>();
    List<DataValue> dataValues = new ArrayList<>(values.length);
    for (MonitoredItemNotification value : values) {
        fieldList.add(fieldNames.get((int) value.getClientHandle() - 1));
        dataValues.add(value.getValue());
    }
    Map<String, ResponseItem<PlcValue>> fields = plcSubscriber.readResponse(fieldList, dataValues);
    final PlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), fields);
    consumers.forEach(plcSubscriptionEventConsumer -> plcSubscriptionEventConsumer.accept(event));
}
Also used : PlcSubscriptionEvent(org.apache.plc4x.java.api.messages.PlcSubscriptionEvent) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem)

Example 4 with DefaultPlcSubscriptionEvent

use of org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent in project plc4x by apache.

the class CANOpenProtocolLogic method publishEvent.

private void publishEvent(CANOpenService service, int nodeId, CANOpenPayload payload) {
    DefaultPlcSubscriptionHandle dispatchedHandle = null;
    for (Map.Entry<DefaultPlcConsumerRegistration, Consumer<PlcSubscriptionEvent>> entry : consumers.entrySet()) {
        DefaultPlcConsumerRegistration registration = entry.getKey();
        Consumer<PlcSubscriptionEvent> consumer = entry.getValue();
        for (PlcSubscriptionHandle handler : registration.getSubscriptionHandles()) {
            CANOpenSubscriptionHandle handle = (CANOpenSubscriptionHandle) handler;
            if (payload instanceof CANOpenPDOPayload) {
                if (handle.matches(service, nodeId)) {
                    logger.trace("Dispatching notification {} for node {} to {}", service, nodeId, handle);
                    dispatchedHandle = handle;
                    CANOpenPDOField field = (CANOpenPDOField) handle.getField();
                    byte[] data = ((CANOpenPDOPayload) payload).getPdo().getData();
                    try {
                        PlcValue value = DataItem.staticParse(new ReadBufferByteBased(data, ByteOrder.LITTLE_ENDIAN), field.getCanOpenDataType(), data.length);
                        DefaultPlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), Collections.singletonMap(handle.getName(), new ResponseItem<>(PlcResponseCode.OK, value)));
                        consumer.accept(event);
                    } catch (ParseException e) {
                        logger.warn("Could not parse data to desired type: {}", field.getCanOpenDataType(), e);
                        DefaultPlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), Collections.singletonMap(handle.getName(), new ResponseItem<>(PlcResponseCode.INVALID_DATA, new PlcNull())));
                        consumer.accept(event);
                    }
                }
            } else if (payload instanceof CANOpenHeartbeatPayload) {
                if (handle.matches(service, nodeId)) {
                    logger.trace("Dispatching notification {} for node {} to {}", service, nodeId, handle);
                    dispatchedHandle = handle;
                    final NMTState state = ((CANOpenHeartbeatPayload) payload).getState();
                    Map<String, PlcValue> fields = new HashMap<>();
                    fields.put("state", new PlcUSINT(state.getValue()));
                    fields.put("node", new PlcUSINT(nodeId));
                    PlcStruct struct = new PlcStruct(fields);
                    DefaultPlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), Collections.singletonMap(handle.getName(), new ResponseItem<>(PlcResponseCode.OK, struct)));
                    consumer.accept(event);
                }
            } else if (payload instanceof CANOpenNetworkPayload) {
                if (handle.matches(service, nodeId)) {
                    logger.trace("Dispatching notification {} for node {} to {}", service, nodeId, handle);
                    dispatchedHandle = handle;
                    final NMTStateRequest state = ((CANOpenNetworkPayload) payload).getRequest();
                    Map<String, PlcValue> fields = new HashMap<>();
                    fields.put("state", new PlcUSINT(state.getValue()));
                    fields.put("node", new PlcUSINT(nodeId));
                    PlcStruct struct = new PlcStruct(fields);
                    DefaultPlcSubscriptionEvent event = new DefaultPlcSubscriptionEvent(Instant.now(), Collections.singletonMap(handle.getName(), new ResponseItem<>(PlcResponseCode.OK, struct)));
                    consumer.accept(event);
                }
            }
        }
    }
    if (dispatchedHandle == null) {
        logger.trace("Could not find subscription matching {} and node {}", service, nodeId);
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PlcUSINT(org.apache.plc4x.java.spi.values.PlcUSINT) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) DefaultPlcSubscriptionHandle(org.apache.plc4x.java.spi.model.DefaultPlcSubscriptionHandle) Consumer(java.util.function.Consumer) PlcStruct(org.apache.plc4x.java.spi.values.PlcStruct) ResponseItem(org.apache.plc4x.java.spi.messages.utils.ResponseItem) DefaultPlcConsumerRegistration(org.apache.plc4x.java.spi.model.DefaultPlcConsumerRegistration) NMTState(org.apache.plc4x.java.canopen.readwrite.NMTState) CANOpenPDOPayload(org.apache.plc4x.java.canopen.readwrite.CANOpenPDOPayload) DefaultPlcSubscriptionEvent(org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent) PlcSubscriptionEvent(org.apache.plc4x.java.api.messages.PlcSubscriptionEvent) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) DefaultPlcSubscriptionHandle(org.apache.plc4x.java.spi.model.DefaultPlcSubscriptionHandle) NMTStateRequest(org.apache.plc4x.java.canopen.readwrite.NMTStateRequest) CANOpenNetworkPayload(org.apache.plc4x.java.canopen.readwrite.CANOpenNetworkPayload) PlcValue(org.apache.plc4x.java.api.value.PlcValue) CANOpenPDOField(org.apache.plc4x.java.canopen.field.CANOpenPDOField) CANOpenHeartbeatPayload(org.apache.plc4x.java.canopen.readwrite.CANOpenHeartbeatPayload) PlcNull(org.apache.plc4x.java.spi.values.PlcNull) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

DefaultPlcSubscriptionEvent (org.apache.plc4x.java.spi.messages.DefaultPlcSubscriptionEvent)4 ResponseItem (org.apache.plc4x.java.spi.messages.utils.ResponseItem)4 HashMap (java.util.HashMap)2 PlcSubscriptionEvent (org.apache.plc4x.java.api.messages.PlcSubscriptionEvent)2 InfluxDBClient (com.influxdb.client.InfluxDBClient)1 WriteApi (com.influxdb.client.WriteApi)1 Point (com.influxdb.client.write.Point)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Consumer (java.util.function.Consumer)1 ConfigurationException (org.apache.commons.configuration2.ex.ConfigurationException)1 PlcConnection (org.apache.plc4x.java.api.PlcConnection)1 PlcException (org.apache.plc4x.java.api.exceptions.PlcException)1 PlcRuntimeException (org.apache.plc4x.java.api.exceptions.PlcRuntimeException)1 PlcSubscriptionRequest (org.apache.plc4x.java.api.messages.PlcSubscriptionRequest)1 PlcSubscriptionResponse (org.apache.plc4x.java.api.messages.PlcSubscriptionResponse)1 PlcSubscriptionHandle (org.apache.plc4x.java.api.model.PlcSubscriptionHandle)1 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)1 PlcValue (org.apache.plc4x.java.api.value.PlcValue)1