[SOLVED] Simple calculations from a rule

I try to do a simple calculation: subtract a number from another number.

I have the following code as a rule

rule "Energy received"

when 
    Item Energy_received_message changed
then
	var Number Pplus_ = 5.0
	var Number Pminus_ = 1.0
	var Number Pdiff_ = Pplus_ - Pminus_
	logInfo('rule', curstate.toString)	
    val String json = (Energy_received_message.state as StringType).toString
	logInfo('rule', json)	
	var Number Pplus = transform("JSONPATH", "$.Pplus", json) 
	logInfo('rule Pplus', Pplus)	
	var Number Pminus = transform("JSONPATH", "$.Pminus", json) 
	logInfo('rule Pminus', Pminus)	
	var Number Pdiff = Pplus - Pminus
	logInfo('rule: Pdiff', Pdiff.toString)	
	
	Power.postUpdate(Pplus.toString)
	Power2.postUpdate(Pminus.toSTring)
	Power3.postUpdate(Pdiff)
end

This gives the following output in my log file
2018-12-27 00:51:04.261 [INFO ] [.eclipse.smarthome.model.script.rule] - 4.0
2018-12-27 00:51:04.283 [INFO ] [.eclipse.smarthome.model.script.rule] - {“Gas”: 283.934, “Date-time_stamp”: “181227005035W”, “Pminus”: 0, “Pplus”: 281}
2018-12-27 00:51:04.301 [INFO ] [se.smarthome.model.script.rule Pplus] - 281
2018-12-27 00:51:04.318 [INFO ] [e.smarthome.model.script.rule Pminus] - 0
2018-12-27 00:51:04.329 [ERROR] [.script.engine.ScriptExecutionThread] - Rule ‘Energy received’: An error occured during the script execution: Could not invoke method: org.eclipse.smarthome.model.script.lib.NumberExtensions.operator_minus(java.lang.Number,java.lang.Number) on instance: null

As you can see, as soon as I work with hard coded values, it seems to work, but when I use values coming from a JSON string, failures occur. The failing line is: var Number Pdiff = Pplus - Pminus

What am I doing wrong?

rule "Energy received"
when 
    Item Energy_received_message changed
then
    var Number Pplus_ = 5.0
    var Number Pminus_ = 1.0
    var Number Pdiff_ = Pplus_ - Pminus_
    logInfo('rule', curstate.toString)
    val String json = (Energy_received_message.state as StringType).toString
    logInfo('rule', json)
    var Number Pplus = Float::parseFloat(transform("JSONPATH", "$.Pplus", json))
    logInfo('rule Pplus', Pplus.toString)
    var Number Pminus = Float::parseFloat(transform("JSONPATH", "$.Pminus", json))
    logInfo('rule Pminus', Pminus.toString)
    var Number Pdiff = Pplus - Pminus
    logInfo('rule: Pdiff', Pdiff.toString)

    Power.postUpdate(Pplus.toString)
    Power2.postUpdate(Pminus.toString)
    Power3.postUpdate(Pdiff)
end

So what you are saying that I tried to store a string in a variable of type Number, and that the assignment itself does not raise an error?

It’spossible, the compiler is trying to assign a type on the fly and makes “guesses” sometimes they don’t work

Your solution works. Thanks.

Please tick the solution mark under the relevant post, thanks