Changing string item to number type in rule?

Gday,

Just trying to get up an alert when a phone battery is getting low. I followed along from this thread (which I think is really awesome) and parsed the battery value from the owntracks mqtt data.

The rest item seems to be updating ok, but is a string type

Item is,
String mqttNWBattery “NW’s Battery [%s%%]”

Rule is,

rule "Battery Alert NW"
when
	Item mqttNWBattery changed 

then
	if((mqttNWBattery.state) < 25){
		sendMail("myemail@gmail.com", "NW battery <25%!", "")
	}
end

I presume I need to change the string item to a decimal type before checking it in the rule math? Not sure how to do that bit.
Could someone point me in the right direction?

Kind Regards,
George

If it is an integer value (i.e. no decimal place) you can do this in your rule:

if(Integer::parseInt(mqttNWBattery.state) < 25)

If it does have a decimal point use Double::parseDouble() instead

However, if you make your Item a Number instead of a String OH should be able to parse the value for you, as long as the String is a parseable number (e.g. no leading or trailing spaces) it will convert it to a DecimalType for you. And if there is something a little off about it you can use a transform to fix it. Then you can do:

if((mqttNWBattery.state as DecimalType) < 25)
1 Like

Rich,

Thanks for your help, I added the line but it gives me an error when the rule is triggered.

Error:
2016-01-28 17:49:47.966 [ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule ‘Battery Alert NW’: Could not invoke method: java.lang.Integer.parseInt(java.lang.String) on instance: null

Do I need to import anything at the top of the rules file?

    rule "Battery Alert NW"
when
	Item mqttNWBattery changed  
	
then
	if(Integer::parseInt(mqttNWBattery.state) < 25){
		sendMail("myemail@gmail.com", "NW battery <25%!", "")
	}
end

Regards,
George

Probably import java.lang.Integer.* should do it :slightly_smiling:

George, is there a reason that your item mqttNWBattery is not a Number item? Following from the other thread, if you define the item as a Number, and then in your mqttPositionPatrikRaw rule you

mqttNWBattery.postUpdate(new DecimalType(transform("JSONPATH", "$.batt", json)))

then your “Battery Alert NW” rule can look like this:

rule "Battery Alert NW"
when
  Item mqttNWBattery changed 
then
  if ((mqttNWBattery.state as DecimalType) < 25) {
    sendMail("myemail@gmail.com", "NW battery is " + mqttNWBattery.state.toString + "%", "")
  }
end

Thanks heaps for the pointers.

Hmmm the only reason for mqttNWBattery not being a Number item is my lack of understanding. Just changed it and it worked.

I pretend I am reasonably tech savy but certainly not a programmer. It has been enjoyable to get a few things up and running, thanks again.

Regards,
George

1 Like