inigoao commented on a change in pull request #257:
URL: https://github.com/apache/plc4x/pull/257#discussion_r663821615



##########
File path: plc4j/integrations/apache-nifi/README.md
##########
@@ -0,0 +1,56 @@
+# PLC4X Apache NiFi Integration
+
+## Plc4xSinkProcessor
+
+## Plc4xSourceProcessor
+
+## Plc4xSourceRecordProcessor
+

Review comment:
       ok. We will add some entries to describe the mapping between PLCResponse 
datatypes and Avro types

##########
File path: 
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/BasePlc4xProcessor.java
##########
@@ -31,46 +32,66 @@ Licensed to the Apache Software Foundation (ASF) under one
 
 public abstract class BasePlc4xProcessor extends AbstractProcessor {
 
-    private static final PropertyDescriptor PLC_CONNECTION_STRING = new 
PropertyDescriptor
+    public static final PropertyDescriptor PLC_CONNECTION_STRING = new 
PropertyDescriptor
         .Builder().name("PLC_CONNECTION_STRING")
         .displayName("PLC connection String")
         .description("PLC4X connection string used to connect to a given PLC 
device.")
         .required(true)
         .addValidator(new Plc4xConnectionStringValidator())
+        
//.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+        //TODO this could be better implemented on a service
         .build();
-    private static final PropertyDescriptor PLC_ADDRESS_STRING = new 
PropertyDescriptor
+    
+    public static final PropertyDescriptor PLC_ADDRESS_STRING = new 
PropertyDescriptor
         .Builder().name("PLC_ADDRESS_STRING")
         .displayName("PLC resource address String")
         .description("PLC4X address string used identify the resource to 
read/write on a given PLC device " +
             "(Multiple values supported). The expected format is: 
{name}={address}(;{name}={address})*")
         .required(true)
         .addValidator(new Plc4xAddressStringValidator())
+        
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
         .build();
 
-    static final Relationship SUCCESS = new Relationship.Builder()
-        .name("SUCCESS")
+    public static final Relationship REL_SUCCESS = new Relationship.Builder()
+        .name("success")
         .description("Successfully processed")
         .build();
-    static final Relationship FAILURE = new Relationship.Builder()
-        .name("FAILURE")
+    public static final Relationship REL_FAILURE = new Relationship.Builder()
+        .name("failure")
         .description("An error occurred processing")
         .build();
 
-    private List<PropertyDescriptor> descriptors;
-
-    Set<Relationship> relationships;
-
-    private String connectionString;
+    //TODO protected could be changed by private with getters
+    protected List<PropertyDescriptor> properties;
+    protected Set<Relationship> relationships;
+  
+    protected String connectionString;
     private Map<String, String> addressMap;
 
     private final PooledPlcDriverManager driverManager = new 
PooledPlcDriverManager();
 
     @Override
     protected void init(final ProcessorInitializationContext context) {
-        this.descriptors = Arrays.asList(PLC_CONNECTION_STRING, 
PLC_ADDRESS_STRING);
-        this.relationships = new HashSet<>(Arrays.asList(SUCCESS, FAILURE));
+       

Review comment:
       It means "added by me", just a reminder while coding. I will remove it.

##########
File path: 
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/BasePlc4xProcessor.java
##########
@@ -31,46 +32,66 @@ Licensed to the Apache Software Foundation (ASF) under one
 
 public abstract class BasePlc4xProcessor extends AbstractProcessor {
 
-    private static final PropertyDescriptor PLC_CONNECTION_STRING = new 
PropertyDescriptor
+    public static final PropertyDescriptor PLC_CONNECTION_STRING = new 
PropertyDescriptor
         .Builder().name("PLC_CONNECTION_STRING")
         .displayName("PLC connection String")
         .description("PLC4X connection string used to connect to a given PLC 
device.")
         .required(true)
         .addValidator(new Plc4xConnectionStringValidator())
+        
//.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+        //TODO this could be better implemented on a service
         .build();
-    private static final PropertyDescriptor PLC_ADDRESS_STRING = new 
PropertyDescriptor
+    
+    public static final PropertyDescriptor PLC_ADDRESS_STRING = new 
PropertyDescriptor
         .Builder().name("PLC_ADDRESS_STRING")
         .displayName("PLC resource address String")
         .description("PLC4X address string used identify the resource to 
read/write on a given PLC device " +
             "(Multiple values supported). The expected format is: 
{name}={address}(;{name}={address})*")
         .required(true)
         .addValidator(new Plc4xAddressStringValidator())
+        
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
         .build();
 
-    static final Relationship SUCCESS = new Relationship.Builder()
-        .name("SUCCESS")
+    public static final Relationship REL_SUCCESS = new Relationship.Builder()
+        .name("success")
         .description("Successfully processed")
         .build();
-    static final Relationship FAILURE = new Relationship.Builder()
-        .name("FAILURE")
+    public static final Relationship REL_FAILURE = new Relationship.Builder()
+        .name("failure")
         .description("An error occurred processing")
         .build();
 
-    private List<PropertyDescriptor> descriptors;
-
-    Set<Relationship> relationships;
-
-    private String connectionString;
+    //TODO protected could be changed by private with getters
+    protected List<PropertyDescriptor> properties;
+    protected Set<Relationship> relationships;
+  
+    protected String connectionString;
     private Map<String, String> addressMap;
 
     private final PooledPlcDriverManager driverManager = new 
PooledPlcDriverManager();
 
     @Override
     protected void init(final ProcessorInitializationContext context) {
-        this.descriptors = Arrays.asList(PLC_CONNECTION_STRING, 
PLC_ADDRESS_STRING);
-        this.relationships = new HashSet<>(Arrays.asList(SUCCESS, FAILURE));
+       
+       //mio
+       final List<PropertyDescriptor> properties = new ArrayList<>();
+       properties.add(PLC_CONNECTION_STRING);
+       properties.add(PLC_ADDRESS_STRING);
+        this.properties = Collections.unmodifiableList(properties);
+
+       
+       final Set<Relationship> relationships = new HashSet<>();
+        relationships.add(REL_SUCCESS);
+        relationships.add(REL_FAILURE);
+        this.relationships = Collections.unmodifiableSet(relationships);
+
     }
 
+    

Review comment:
       I think we were planning to use it from Plc4xSourceRecordProcessor.. we 
could change it to protected?

##########
File path: 
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/BasePlc4xProcessor.java
##########
@@ -142,6 +163,7 @@ public ValidationResult validate(String subject, String 
input, ValidationContext
         @Override
         public ValidationResult validate(String subject, String input, 
ValidationContext context) {
             // TODO: Add validation here ...

Review comment:
       Ok. Are we allowed to open a JIRA for this? Is there any documentation 
about how to do it?

##########
File path: 
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSourceRecordProcessor.java
##########
@@ -0,0 +1,201 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+package org.apache.plc4x.nifi;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.components.PropertyValue;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.flowfile.attributes.CoreAttributes;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.ProcessorInitializationContext;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.util.StopWatch;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
+import org.apache.plc4x.java.api.messages.PlcReadRequest;
+import org.apache.plc4x.java.api.messages.PlcReadResponse;
+import org.apache.plc4x.nifi.record.Plc4xWriter;
+import org.apache.plc4x.nifi.record.RecordPlc4xWriter;
+
+@Tags({ "plc4x-source" })
+@InputRequirement(InputRequirement.Requirement.INPUT_ALLOWED)
+@CapabilityDescription("Processor able to read data from industrial PLCs using 
Apache PLC4X")
+@WritesAttributes({ @WritesAttribute(attribute = "value", description = "some 
value") })
+public class Plc4xSourceRecordProcessor extends BasePlc4xProcessor {
+
+       public static final String RESULT_ROW_COUNT = "plc4x.read.row.count";
+       public static final String RESULT_QUERY_DURATION = 
"plc4x.read.query.duration";
+       public static final String RESULT_QUERY_EXECUTION_TIME = 
"plc4x.read.query.executiontime";
+       public static final String RESULT_QUERY_FETCH_TIME = 
"plc4x.read.query.fetchtime";
+       public static final String INPUT_FLOWFILE_UUID = "input.flowfile.uuid";
+       public static final String RESULT_ERROR_MESSAGE = 
"plc4x.read.error.message";
+
+       public static final PropertyDescriptor RECORD_WRITER_FACTORY = new 
PropertyDescriptor.Builder().name("plc4x-record-writer").displayName("Record 
Writer")
+                       .description("Specifies the Controller Service to use 
for writing results to a FlowFile. The Record Writer may use Inherit Schema to 
emulate the inferred schema behavior, i.e. "
+                                       + "an explicit schema need not be 
defined in the writer, and will be supplied by the same logic used to infer the 
schema from the column types.")
+                       
.identifiesControllerService(RecordSetWriterFactory.class)
+                       .required(true)
+                       .build();
+
+       public Plc4xSourceRecordProcessor() {
+       }
+
+       @Override
+       protected void init(final ProcessorInitializationContext context) {
+               super.init(context);
+               final Set<Relationship> r = new HashSet<>();
+               r.addAll(super.getRelationships());
+               this.relationships = Collections.unmodifiableSet(r);
+
+               final List<PropertyDescriptor> pds = new ArrayList<>();
+               pds.addAll(super.getSupportedPropertyDescriptors());
+               pds.add(RECORD_WRITER_FACTORY);
+               this.properties = Collections.unmodifiableList(pds);
+       }
+
+       @OnScheduled
+       @Override
+       public void onScheduled(final ProcessContext context) {
+        super.connectionString = 
context.getProperty(PLC_CONNECTION_STRING.getName()).getValue();
+    }
+       
+       @Override
+       public void onTrigger(final ProcessContext context, final 
ProcessSession session) throws ProcessException {
+               FlowFile fileToProcess = null;
+               // TODO: In the future the processor will be configurable to 
get the address and
+               // the connection from incoming flowfile
+               if (context.hasIncomingConnection()) {
+                       fileToProcess = session.get();
+                       // If we have no FlowFile, and all incoming connections 
are self-loops then we
+                       // can continue on.
+                       // However, if we have no FlowFile and we have 
connections coming from other
+                       // Processors, then we know that we should run only if 
we have a FlowFile.
+                       if (fileToProcess == null && 
context.hasNonLoopConnection()) {
+                               return;
+                       }
+               }
+
+               // TODO: this could be enhanced checking if address map should 
be updated (via a cache boolean, checking property values is a nifi expression 
language, etc)
+               Map<String, String> addressMap = new HashMap<>();
+        PropertyValue addresses = 
context.getProperty(PLC_ADDRESS_STRING.getName());
+        for (String segment : 
addresses.evaluateAttributeExpressions(fileToProcess).getValue().split(";")) {
+            String[] parts = segment.split("=");
+            if(parts.length != 2) {
+                throw new ProcessException("Invalid address format");
+            }
+            addressMap.put(parts[0], parts[1]);
+        }
+               
+               
+               final List<FlowFile> resultSetFlowFiles = new ArrayList<>();
+
+               Plc4xWriter plc4xWriter = new 
RecordPlc4xWriter(context.getProperty(RECORD_WRITER_FACTORY).asControllerService(RecordSetWriterFactory.class),
 fileToProcess == null ? Collections.emptyMap() : 
fileToProcess.getAttributes());
+               final ComponentLog logger = getLogger();
+               // Get an instance of a component able to read from a PLC.
+               // TODO: Change this to use NiFi service instead of direct 
connection
+               final AtomicLong nrOfRows = new AtomicLong(0L);
+               final StopWatch executeTime = new StopWatch(true);
+
+               try (PlcConnection connection = 
getDriverManager().getConnection(getConnectionString())) {
+
+                       String inputFileUUID = fileToProcess == null ? null : 
fileToProcess.getAttribute(CoreAttributes.UUID.key());
+                       Map<String, String> inputFileAttrMap = fileToProcess == 
null ? null : fileToProcess.getAttributes();
+                       FlowFile resultSetFF;
+                       if (fileToProcess == null) {
+                               resultSetFF = session.create();
+                       } else {
+                               resultSetFF = session.create(fileToProcess);
+                       }
+                       if (inputFileAttrMap != null) {
+                               resultSetFF = 
session.putAllAttributes(resultSetFF, inputFileAttrMap);
+                       }
+
+                       PlcReadRequest.Builder builder = 
connection.readRequestBuilder();
+                       addressMap.keySet().forEach(field -> {
+                               String address = addressMap.get(field);
+                               if (address != null) {
+                                       builder.addItem(field, address);
+                               }
+                       });
+                       PlcReadRequest readRequest = builder.build();

Review comment:
       Yes you are right. We will take a closer look and make some tests for 
this. We will adapt the code to handle timeout.

##########
File path: 
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/Plc4xReadResponseRecordSet.java
##########
@@ -0,0 +1,130 @@
+package org.apache.plc4x.nifi.record;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.avro.Schema;
+import org.apache.nifi.avro.AvroTypeUtil;
+import org.apache.nifi.serialization.record.MapRecord;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordField;
+import org.apache.nifi.serialization.record.RecordSchema;
+import org.apache.nifi.serialization.record.RecordSet;
+import org.apache.plc4x.java.api.messages.PlcReadResponse;
+import org.apache.plc4x.java.api.value.PlcValue;
+import org.apache.plc4x.nifi.util.Plc4xCommon;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class Plc4xReadResponseRecordSet implements RecordSet, Closeable {
+    private static final Logger logger = 
LoggerFactory.getLogger(Plc4xReadResponseRecordSet.class);
+    private final PlcReadResponse readResponse;
+    private final Set<String> rsColumnNames;
+    private boolean moreRows;
+
+    // TODO: review this AtomicReference?
+       // TODO: this could be enhanced checking if record schema should be 
updated (via a cache boolean, checking property values is a nifi expression 
language, etc)
+       private AtomicReference<RecordSchema> recordSchema;
+
+    public Plc4xReadResponseRecordSet(final PlcReadResponse readResponse) 
throws IOException {
+        this.readResponse = readResponse;
+        moreRows = true;
+        
+        logger.debug("Creating record schema from PlcReadResponse");
+        Map<String, ? extends PlcValue> responseDataStructure = 
readResponse.getAsPlcValue().getStruct();
+        rsColumnNames = responseDataStructure.keySet();
+        
+        if (recordSchema == null) {
+               Schema avroSchema = 
Plc4xCommon.createSchema(responseDataStructure); //TODO review this method as 
it is the 'mapping' from PlcValues to avro datatypes          
+               recordSchema = new AtomicReference<RecordSchema>();
+               recordSchema.set(AvroTypeUtil.createSchema(avroSchema));
+        }
+        logger.debug("Record schema from PlcReadResponse successfuly 
created.");
+
+    }
+
+    
+    @Override
+    public RecordSchema getSchema() {
+        return this.recordSchema.get();
+    }
+
+    // Protected methods for subclasses to access private member variables
+    protected PlcReadResponse getReadResponse() {
+        return readResponse;
+    }
+
+    protected boolean hasMoreRows() {
+        return moreRows;
+    }
+
+    protected void setMoreRows(boolean moreRows) {
+        this.moreRows = moreRows;
+    }
+
+    @Override
+    public Record next() throws IOException {
+        if (moreRows) {
+             final Record record = createRecord(readResponse);
+             setMoreRows(false);
+             return record;
+        } else {
+             return null;
+        }
+    }
+
+    @Override
+    public void close() {
+        //do nothing
+    }
+
+    protected Record createRecord(final PlcReadResponse readResponse) throws 
IOException{
+        final Map<String, Object> values = new 
HashMap<>(getSchema().getFieldCount());
+
+        logger.debug("creating record.");
+
+        for (final RecordField field : getSchema().getFields()) {
+            final String fieldName = field.getFieldName();
+
+            final Object value;
+            
+            //TODO
+            if (rsColumnNames.contains(fieldName)) {
+               value = normalizeValue(readResponse.getObject(fieldName));
+            } else {
+                value = null;
+            }
+            //TODO we are asuming that record schema is always inferred from 
request, not writen by the user, so maybe previous lines could be changed by 
the following one
+           // value = normalizeValue(readResponse.getObject(fieldName));
+            

Review comment:
       I dont understand what does the .trace mean.. could you please provide 
further info about it?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@plc4x.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to