Skip to content

Commit c4d4037

Browse files
authored
Merge pull request #5 from paulorb/logging
Logging
2 parents 8abc256 + f811a57 commit c4d4037

File tree

11 files changed

+112
-44
lines changed

11 files changed

+112
-44
lines changed

build.gradle.kts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,24 @@ repositories {
2020
}
2121
}
2222

23+
val log4jVersion = "2.12.1"
2324

2425
dependencies {
2526
kapt("info.picocli:picocli-codegen:4.6.1")
2627
implementation ("info.picocli:picocli:4.6.1")
2728
implementation("javax.xml.bind:jaxb-api:2.3.1")
2829
implementation("com.sun.xml.bind:jaxb-core:2.3.0.1")
2930
implementation("com.sun.xml.bind:jaxb-impl:2.3.3")
30-
implementation ("com.github.paulorb:modbus-kt:1.0.12")
31+
implementation ("com.github.paulorb:modbus-kt:1.0.14")
3132
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
3233
implementation("org.apache.commons:commons-csv:1.10.0")
34+
implementation("org.apache.logging.log4j:log4j-core:$log4jVersion")
35+
implementation("org.apache.logging.log4j:log4j-api:$log4jVersion")
36+
implementation("org.apache.logging.log4j:log4j-slf4j-impl:$log4jVersion")
3337
testImplementation(kotlin("test"))
3438
}
3539

40+
3641
kapt {
3742
arguments {
3843
arg("project", "${project.group}/${project.name}")

src/main/kotlin/Main.kt

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import picocli.CommandLine.Model.CommandSpec
66
import java.util.*
77
import java.util.concurrent.Callable
88
import kotlin.system.exitProcess
9-
9+
import org.apache.logging.log4j.core.config.Configurator
10+
import org.slf4j.LoggerFactory
1011

1112
data class EnvParameter(
1213
var symbol : String,
@@ -50,6 +51,10 @@ class Checksum : Callable<Int> {
5051
private lateinit var modbusServer: ModbusServer
5152
private lateinit var environmentParameters: List<EnvParameter>
5253

54+
companion object {
55+
val logger = LoggerFactory.getLogger("main")
56+
}
57+
5358
private fun processEnvironmentParameters(parameters: MutableList<String?>?): List<EnvParameter> {
5459
val envParameter = mutableListOf<EnvParameter>()
5560
parameters?.forEach { param ->
@@ -66,17 +71,18 @@ class Checksum : Callable<Int> {
6671
}
6772

6873
override fun call(): Int {
74+
Configurator.initialize(null, "log4j2.xml")
6975
val mainCoroutineScope = CoroutineScope(Dispatchers.Default)
7076
val configuration = ConfigurationParser()
7177

7278
if(simulationRandomValues && file.isNotEmpty()){
73-
println("-f and -sr cannot be mixed, one of the simulations must be chosen")
79+
logger.error("-f and -sr cannot be mixed, one of the simulations must be chosen")
7480
return -1
7581
}
7682

7783
environmentParameters = processEnvironmentParameters(parameters)
7884
if(environmentParameters.isNotEmpty()){
79-
println("environment parameters: ${environmentParameters.toString()}")
85+
logger.info("environment parameters: ${environmentParameters.toString()}")
8086
}
8187

8288
//val fileContents = Files.readAllBytes(file.toPath())

src/main/kotlin/PlcMemory.kt

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import org.slf4j.LoggerFactory
12
import java.util.InvalidPropertiesFormatException
23
import java.util.concurrent.ConcurrentHashMap
34

@@ -10,6 +11,10 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
1011
private var holdingRegister: ConcurrentHashMap<Int, Short> = ConcurrentHashMap()
1112
private var device = configurationParser.getConfiguredDevice()
1213

14+
companion object {
15+
val logger = LoggerFactory.getLogger("PlcMemory")
16+
}
17+
1318
init {
1419
device.configuration.registers.register.forEach { register ->
1520
when(register.addressType){
@@ -37,15 +42,15 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
3742

3843
//0x
3944
override fun forceMultipleCoils(addressValueList: MutableList<Pair<Int, Boolean>>) {
40-
println("(0x) forceMultipleCoils")
45+
logger.debug("(0x) forceMultipleCoils")
4146
addressValueList.forEach { coil ->
4247
coils[coil.first] = coil.second
4348
}
4449
}
4550

4651
//0x
4752
override fun forceSingleCoil(address: Int, value: Boolean) {
48-
println("(0x) forceSingleCoil")
53+
logger.debug("(0x) forceSingleCoil")
4954
coils[address] = value
5055
}
5156

@@ -61,7 +66,7 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
6166

6267
// 4x
6368
override fun presetMultipleRegisters(addressValueList: MutableList<Pair<Int, Short>>) {
64-
println("(4x) presetMultipleRegisters")
69+
logger.debug("(4x) presetMultipleRegisters")
6570
addressValueList.forEach { register ->
6671
holdingRegister[register.first] = register.second
6772
}
@@ -70,13 +75,13 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
7075

7176

7277
override fun presetSingleRegister(address: Int, value: Boolean) {
73-
println("presetSingleRegister")
78+
logger.debug("presetSingleRegister")
7479
TODO("Not yet implemented")
7580
}
7681

7782
// 0x Registers
7883
override fun readCoilStatus(startAddress: Int, numberOfRegisters: Int): List<Boolean> {
79-
println("(0x) readCoilStatus")
84+
logger.debug("(0x) readCoilStatus")
8085
val listCoils = mutableListOf<Boolean>()
8186
for(i in startAddress until startAddress + numberOfRegisters) {
8287
if(coils[i] != null){
@@ -90,14 +95,14 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
9095

9196
// 4x
9297
override fun readHoldingRegister(startAddress: Int, numberOfRegisters: Int): List<Short> {
93-
println("(4x) readHoldingRegister")
98+
logger.debug("(4x) readHoldingRegister")
9499
val listHoldingRegisters = mutableListOf<Short>()
95100
for(i in startAddress until startAddress + numberOfRegisters) {
96101
if(holdingRegister[i] != null){
97-
println("readHoldingRegister address $i value=${holdingRegister[i]}")
102+
logger.debug("readHoldingRegister address $i value=${holdingRegister[i]}")
98103
listHoldingRegisters.add(holdingRegister[i]!!)
99104
}else{
100-
println("readHoldingRegister address $i value=0")
105+
logger.debug("readHoldingRegister address $i value=0")
101106
listHoldingRegisters.add(0)
102107
}
103108
}
@@ -106,7 +111,7 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
106111

107112
// 3x register
108113
override fun readInputRegister(startAddress: Int, numberOfRegisters: Int): List<Short> {
109-
println("(3x) readInputRegister")
114+
logger.debug("(3x) readInputRegister")
110115
val listInputRegisters = mutableListOf<Short>()
111116
for(i in startAddress until startAddress + numberOfRegisters) {
112117
if(inputRegister[i] != null){
@@ -120,7 +125,7 @@ class PlcMemory(configurationParser: ConfigurationParser) : IModbusServerEventL
120125

121126
// 1x register
122127
override fun readInputStatus(startAddress: Int, numberOfRegisters: Int): List<Boolean> {
123-
println("readInputStatus")
128+
logger.debug("readInputStatus")
124129
val listCoils = mutableListOf<Boolean>()
125130
for(i in startAddress until startAddress + numberOfRegisters) {
126131
if(inputStatus[i] != null){

src/main/kotlin/PlcSimulation.kt

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import kotlinx.coroutines.*
22
import operations.*
3+
import org.slf4j.LoggerFactory
34
import java.lang.Float
45
import java.rmi.NotBoundException
56
import java.util.*
@@ -16,6 +17,11 @@ class PlcSimulation(
1617
val addOperation = AddOperation(configurationParser.getConfiguredDevice().configuration, memory, parameters)
1718
val setOperation = SetOperation(configurationParser.getConfiguredDevice().configuration, memory, parameters)
1819
val subOperation = SubOperation(configurationParser.getConfiguredDevice().configuration, memory, parameters)
20+
21+
companion object {
22+
val logger = LoggerFactory.getLogger("PlcSimulation")
23+
}
24+
1925
init {
2026
var simulationConfiguration = configurationParser.getConfiguredDevice().simulation
2127
var configuration = configurationParser.getConfiguredDevice().configuration
@@ -34,9 +40,9 @@ class PlcSimulation(
3440
}
3541
}
3642
} catch (e: Exception) {
37-
println("Exception - ${e.message}")
43+
logger.error("Exception - ${e.message}")
3844
} finally {
39-
println("Job: Finally block, cleaning up resources")
45+
logger.error("Job: Finally block, cleaning up resources")
4046
}
4147
}
4248

@@ -53,7 +59,7 @@ class PlcSimulation(
5359
}
5460

5561
is Delay -> {
56-
println("Delay value ${element.value}")
62+
logger.info("Delay value ${element.value}")
5763
delay(element.value.toLong())
5864
}
5965

@@ -85,7 +91,7 @@ class PlcSimulation(
8591

8692

8793
suspend fun ifEqual(element: IfEqual, configuration: Configuration, memory: PlcMemory) {
88-
println("IfEqual symbol ${element.symbol} value ${element.value}")
94+
logger.info("IfEqual symbol ${element.symbol} value ${element.value}")
8995
var value = processValue(element.value)
9096
var variable = configuration.registers.getVarConfiguration(element.symbol)
9197
if (variable == null) {
@@ -113,11 +119,11 @@ class PlcSimulation(
113119
processOperationElement(subElement, configuration, memory)
114120
}
115121
}else {
116-
println("ERROR: Symbol ${element.symbol} has invalid datatype during IfEqual execution")
122+
logger.error("Symbol ${element.symbol} has invalid datatype during IfEqual execution")
117123
}
118124

119125
}else {
120-
println("ERROR: Symbol ${element.symbol} not found during IfEqual execution")
126+
logger.error("Symbol ${element.symbol} not found during IfEqual execution")
121127
throw CancellationException("Error - IfEqual")
122128
}
123129
} else {
@@ -132,7 +138,7 @@ class PlcSimulation(
132138
if (variable.datatype == "FLOAT32") {
133139
var currentValue = memory.readHoldingRegister(variable.address.toInt(), 2)
134140
if(currentValue.isEmpty()){
135-
println("ERROR: Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
141+
logger.error("Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
136142
throw CancellationException("Error - Add")
137143
}
138144
val intValue = (( currentValue[1].toInt() shl 16) or (currentValue[0].toInt() and 0xFFFF))
@@ -153,7 +159,7 @@ class PlcSimulation(
153159
} else {
154160
var currentValue = memory.readHoldingRegister(variable.address.toInt(), 1)
155161
if(currentValue.isEmpty()){
156-
println("ERROR: IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
162+
logger.error("IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
157163
throw CancellationException("Error - IfEqual")
158164
}
159165
//compare
@@ -172,7 +178,7 @@ class PlcSimulation(
172178
AddressType.INPUT_REGISTER -> {
173179
val currentValue = memory.readInputRegister(variable.address.toInt(), 1)
174180
if(currentValue.isEmpty()){
175-
println("ERROR: IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
181+
logger.error("IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
176182
throw CancellationException("Error - IfEqual")
177183
}
178184
//compare
@@ -188,11 +194,11 @@ class PlcSimulation(
188194
}
189195
AddressType.COIL -> {
190196
if ( (element.value != "0" && element.value != "1")) {
191-
println("ERROR: Invalid value format on IfEqual. Symbol ${element.symbol} is of BOOL type and supports only values 0 or 1 not ${element.value} for comparison")
197+
logger.error("Invalid value format on IfEqual. Symbol ${element.symbol} is of BOOL type and supports only values 0 or 1 not ${element.value} for comparison")
192198
}
193199
var currentValue = memory.readCoilStatus(variable.address.toInt(), 2)
194200
if(currentValue.isEmpty()){
195-
println("ERROR: IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
201+
logger.error("IfEqual Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
196202
throw CancellationException("Error - IfEqual")
197203
}
198204
//compare

src/main/kotlin/operations/AddOperation.kt

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,27 @@ import Configuration
44
import PlcMemory
55
import Add
66
import EnvironmentVariables
7+
import org.slf4j.LoggerFactory
78
import java.util.concurrent.CancellationException
89
import toBooleanFromBinary
910

1011
class AddOperation(private val configuration: Configuration,private val memory: PlcMemory, environmentVariables: EnvironmentVariables
1112
) : BaseOperation(environmentVariables, configuration) {
13+
14+
companion object {
15+
val logger = LoggerFactory.getLogger("AddOperation")
16+
}
17+
1218
fun addOperation(element: Add){
13-
println("Add symbol ${element.symbol} value ${element.value}")
19+
logger.info("Add symbol ${element.symbol} value ${element.value}")
1420
var value = processValue(element.value)
1521
var variable = configuration.registers.getVarConfiguration(element.symbol)
1622
if (variable == null) {
17-
println("ERROR: Symbol ${element.symbol} not found during Set execution")
23+
logger.error("Symbol ${element.symbol} not found during Set execution")
1824
throw CancellationException("Error - Add")
1925
} else {
2026
if(variable.addressType == AddressType.COIL || variable.addressType == AddressType.DISCRETE_INPUT){
21-
println("ERROR: Symbol ${element.symbol} is of type COIL or DISCRETE_INPUT which is not support by Add operation")
27+
logger.error("Symbol ${element.symbol} is of type COIL or DISCRETE_INPUT which is not support by Add operation")
2228
throw CancellationException("Error - Add")
2329
}
2430

@@ -32,7 +38,7 @@ class AddOperation(private val configuration: Configuration,private val memory:
3238
if (variable.datatype == "FLOAT32") {
3339
var currentValue = memory.readHoldingRegister(variable.address.toInt(), 2)
3440
if(currentValue.isEmpty()){
35-
println("ERROR: Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
41+
logger.error("Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
3642
throw CancellationException("Error - Add")
3743
}
3844
val intValue = (( currentValue[1].toInt() shl 16) or (currentValue[0].toInt() and 0xFFFF))
@@ -43,7 +49,7 @@ class AddOperation(private val configuration: Configuration,private val memory:
4349
} else {
4450
var currentValue = memory.readHoldingRegister(variable.address.toInt(), 1)
4551
if(currentValue.isEmpty()){
46-
println("ERROR: Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
52+
logger.error("Add Operation - Unable to get value of ${element.symbol} address ${variable.address} ")
4753
throw CancellationException("Error - Add")
4854
}
4955
var intValue = value.toInt()

src/main/kotlin/operations/CsvOperation.kt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import Csv
55
import PlcMemory
66
import org.apache.commons.csv.CSVFormat
77
import org.apache.commons.csv.CSVParser
8+
import org.slf4j.LoggerFactory
89
import java.io.FileReader
910
import java.nio.file.Paths
1011
import java.util.concurrent.CancellationException
@@ -13,6 +14,9 @@ data class CsvOperationInfo(var position: Int, var csvColumn: List<String>)
1314
class CsvOperation {
1415
private var csvVariables: MutableMap<String, CsvOperationInfo> = mutableMapOf<String, CsvOperationInfo>()
1516

17+
companion object {
18+
val logger = LoggerFactory.getLogger("CsvOperation")
19+
}
1620
@Throws(InternalError::class)
1721
private fun parseCsv(csvFileName: String, column: Int) : List<String> {
1822
val columnValues = mutableListOf<String>()
@@ -50,9 +54,10 @@ class CsvOperation {
5054
}
5155
fun process(element: Csv, configuration: Configuration, memory: PlcMemory) {
5256
var nextValue = getNextValue(element)
57+
AddOperation.logger.info("Csv symbol ${element.symbol} value $nextValue")
5358
var variable = configuration.registers.getVarConfiguration(element.symbol)
5459
if (variable == null) {
55-
println("ERROR: Symbol ${element.symbol} not found during CSV execution")
60+
logger.error("Symbol ${element.symbol} not found during CSV execution")
5661
throw CancellationException("Error - CSV")
5762
} else {
5863
when (variable.addressType) {

src/main/kotlin/operations/LinearOperation.kt

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,16 @@ package operations
33
import Configuration
44
import PlcMemory
55
import Linear
6+
import org.slf4j.LoggerFactory
67
import java.util.concurrent.CancellationException
78

89
class LinearOperation {
910
private var linearVariables: MutableMap<String, Double> = mutableMapOf<String, Double>()
1011

12+
companion object {
13+
val logger = LoggerFactory.getLogger("LinearOperation")
14+
}
15+
1116
private fun getNextValue(linear: Linear): String {
1217
var x =0.0
1318
if(linear.endX > linear.startX) {
@@ -36,13 +41,14 @@ class LinearOperation {
3641

3742
fun process(element: Linear, configuration: Configuration, memory: PlcMemory) {
3843
var nextValue = getNextValue(element)
44+
logger.info("Linear symbol ${element.symbol} value $nextValue")
3945
var variable = configuration.registers.getVarConfiguration(element.symbol)
4046
if (variable == null) {
41-
println("ERROR: Symbol ${element.symbol} not found during Linear execution")
47+
logger.error("Symbol ${element.symbol} not found during Linear execution")
4248
throw CancellationException("Error - Linear")
4349
} else {
4450
if (variable.addressType == AddressType.COIL || variable.addressType == AddressType.DISCRETE_INPUT) {
45-
println("ERROR: Symbol ${element.symbol} is of type COIL or DISCRETE_INPUT which is not support by Linear operation")
51+
logger.error("Symbol ${element.symbol} is of type COIL or DISCRETE_INPUT which is not support by Linear operation")
4652
throw CancellationException("Error - Linear")
4753
}
4854

0 commit comments

Comments
 (0)