Casting a String to a Number/Decimal - not working

Hi, I’ve tried a couple of different combinations as to cast the String variable “Arduino” to a Number variable “Weight”. What did I do wrong in this instance.
P.S. I’m trying to change it into a Number variable as I am trying to store it into a database (rrd4j) in order to create a chart/graph.

error:
2016-04-23 21:06:27.055 [ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule ‘Arduino sends to Openhab’: Cannot cast org.openhab.core.library.types.StringType to org.openhab.core.library.types.DecimalType

rules:
import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import java.lang.Integer
import java.lang.Double
import java.lang.String

rule "Arduino sends to Openhab"
when
Item Arduino received update
then
var Number newWeight = (Arduino.state as DecimalType).intValue
Weight.postUpdate(newWeight)
end

Not sure about the syntax here, however in Java it should look like this Float.parsefloat (Arduino. State)
Why didn’t you start of with a number variable for Arduino?

1 Like

I agree with @opus that, if possible, you should use a Number item to hold this value, so you won’t need something like

var Number newWeight = Integer::parseInt(Arduino.state.toString)

but would be able to use this directly:

Weight.postUpdate(Arduino.state)

In which case you don’t even need the rule; just update the Weight item from your Arduino directly.

In any case, you should not need any of these imports:

import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import java.lang.Integer
import java.lang.Double
import java.lang.String
1 Like

The arduino can only send a string though the serial port from what I know/read

If Arduino is a String Item you can’t simply cast it to a DecimalType. You need to parse the value into a Number.

You have to reference static methods using “::” instead of “.”

Float::parseFloat(Arduino.state)

As long as the String the Arduino sends is parsable you can just do what @watou recommends and just send the String on to Weight as is without modification. OH will parse it for you.

1 Like