Skip to content

Commit

Permalink
Added random operation
Browse files Browse the repository at this point in the history
  • Loading branch information
paulorb committed Jan 24, 2024
1 parent 7b5b1b3 commit e5f700b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/kotlin/PlcSimulation.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PlcSimulation(
}

is Random -> {
println("Random symbol ${element.symbol} valueMax ${element.valueMax} valueMin ${element.valueMin}")
randomOperation(element, configuration, memory)
}

is Delay -> {
Expand Down
47 changes: 47 additions & 0 deletions src/main/kotlin/operations/RandomOperation.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package operations

import AddressType
import Configuration
import PlcMemory
import Random
import java.util.concurrent.CancellationException


fun randomOperation(element: Random, configuration: Configuration, memory: PlcMemory){
println("Random symbol ${element.symbol} value min ${element.valueMin} value max ${element.valueMax}")
var variable = configuration.registers.getVarConfiguration(element.symbol)
if (variable == null) {
println("ERROR: Symbol ${element.symbol} not found during Set execution")
throw CancellationException("Error - Random")
} else {
if(variable.addressType == AddressType.COIL || variable.addressType == AddressType.DISCRETE_INPUT){
println("ERROR: Symbol ${element.symbol} is of type COIL or DISCRETE_INPUT which is not support by Random operation")
throw CancellationException("Error - Random")
}

when (variable.addressType) {

AddressType.HOLDING_REGISTER -> {
//get the current value
//add
//set back the new value

if (variable.datatype == "FLOAT32") {
val random: Float = element.valueMin.toFloat() + kotlin.random.Random.nextFloat() * (element.valueMax.toFloat() - element.valueMin.toFloat())
setHoldingRegisterFloat32(random, memory, variable)
} else {
val random: Int = element.valueMin.toInt() + kotlin.random.Random.nextInt() * (element.valueMax.toInt() - element.valueMin.toInt())
setHoldingRegisterInt16(memory, variable, random.toShort())
}
}
AddressType.INPUT_REGISTER -> {
val random: Int = element.valueMin.toInt() + kotlin.random.Random.nextInt() * (element.valueMax.toInt() - element.valueMin.toInt())
memory.setInputRegister(variable.address.toInt(),random.toShort())
}

else -> {
throw CancellationException("Error - Random")
}
}
}
}

0 comments on commit e5f700b

Please sign in to comment.