1
+ package operations
2
+
3
+ import Configuration
4
+ import Csv
5
+ import PlcMemory
6
+ import org.apache.commons.csv.CSVFormat
7
+ import org.apache.commons.csv.CSVParser
8
+ import java.io.FileReader
9
+ import java.nio.file.Paths
10
+ import java.util.concurrent.CancellationException
11
+
12
+ data class CsvOperationInfo (var position : Int , var csvColumn : List <String >)
13
+ class CsvOperation {
14
+ private var csvVariables: MutableMap <String , CsvOperationInfo > = mutableMapOf<String , CsvOperationInfo >()
15
+
16
+ @Throws(InternalError ::class )
17
+ private fun parseCsv (csvFileName : String , column : Int ) : List <String > {
18
+ val columnValues = mutableListOf<String >()
19
+ try {
20
+ var newPath = Paths .get(Paths .get(ConfigurationParser .fileName).parent.toString(), csvFileName)
21
+ FileReader ( newPath.toString()).use { fileReader ->
22
+ val csvParser = CSVParser (fileReader, CSVFormat .DEFAULT )
23
+ for (csvRecord in csvParser) {
24
+ columnValues.add( csvRecord.get(column))
25
+ }
26
+ }
27
+ } catch (e: Exception ) {
28
+ throw InternalError (" Error reading csv file" )
29
+ }
30
+ return columnValues
31
+ }
32
+
33
+
34
+ private fun getNextValue (csv : Csv ): String {
35
+ if (! csvVariables.containsKey(csv.symbol)){
36
+ csvVariables[csv.symbol] = CsvOperationInfo (csv.startRow,parseCsv(csv.file,csv.column))
37
+ }
38
+ val currentValue = csvVariables[csv.symbol]!! .csvColumn[csvVariables[csv.symbol]!! .position]
39
+ csvVariables[csv.symbol]!! .position++
40
+ if (csvVariables[csv.symbol]!! .position > csvVariables[csv.symbol]!! .csvColumn.size - 1 ||
41
+ (csv.endRow != - 1 && csvVariables[csv.symbol]!! .position > csv.endRow)
42
+ ){
43
+ if (csv.replay){
44
+ csvVariables[csv.symbol]!! .position = csv.startRow
45
+ }else {
46
+ csvVariables[csv.symbol]!! .position--
47
+ }
48
+ }
49
+ return currentValue
50
+ }
51
+ fun process (element : Csv , configuration : Configuration , memory : PlcMemory ) {
52
+ var nextValue = getNextValue(element)
53
+ var variable = configuration.registers.getVarConfiguration(element.symbol)
54
+ if (variable == null ) {
55
+ println (" ERROR: Symbol ${element.symbol} not found during CSV execution" )
56
+ throw CancellationException (" Error - CSV" )
57
+ } else {
58
+ when (variable.addressType) {
59
+
60
+ AddressType .HOLDING_REGISTER -> {
61
+ // get the current value
62
+ // add
63
+ // set back the new value
64
+
65
+ if (variable.datatype == " FLOAT32" ) {
66
+
67
+ setHoldingRegisterFloat32(nextValue.toFloat(), memory, variable)
68
+ } else {
69
+
70
+ setHoldingRegisterInt16(memory, variable, nextValue.toFloat().toInt().toShort())
71
+ }
72
+ }
73
+
74
+ AddressType .INPUT_REGISTER -> {
75
+ memory.setInputRegister(variable.address.toInt(), nextValue.toFloat().toInt().toShort())
76
+ }
77
+
78
+ else -> {
79
+ throw CancellationException (" Error - Linear" )
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ }
0 commit comments