Rule not working after upgrading to OpenHab 2

I recently upgraded from Openhab 1.83 to OpenHab 2.1 and my rules stopped working. Some were fixed by removing the “import” sections. However that didn’t help for the rule below (it is to calculate the gas usage per hour).
What should I change to make it work on OpenHab 2.1?

import org.joda.time.*
import org.openhab.core.library.types.*
import org.openhab.model.script.actions.*

var float last_gasmeter
var DateTime last_time

rule Gas_per_hour
when
	Item Gasmeter received update
then
	var current_gasmeter  = Gasmeter.state as float
	var DateTime current_time = now
	var dt = current_time.millis - last_time.millis
	var dgas = current_gasmeter - last_gasmeter 
	postUpdate(Gas_per_uur, (dgas / (3600.0f * dt)))
	last_gasmeter = current_gasmeter as float
	last_time = current_time
end

I got the error “Cannot cast from state to float” before I changed to

var float current_gasmeter = Float::parseFloat(Gasmeter.state.toString)

If you have any questions about syntax you should first load the file in Designer to see if it detects any syntax errors.

And perhaps even before that, you should look at the logs for errors.

At a quick glance, I would say that you should:

  • remove the imports

  • cast the state of Gasmeter to Number, not float. I’m frankly astonished this ever worked as written. If you insist on keeping it a float, then call .toFloat:

    var current_gasmeter = (Gasmeter.state as Number).toFloat

  • the postUpdate Action requires a String as both arguments. Try using the sendCommand method instead

    Gas_per_uur.sendCommand(dgas / (3600.0 * dt))

Thanks all, your tips helped me fix it.
The rule above was actually an older version of rule, so I was trying to fix the wrong rule (you can find the later version here ). The SmartHome Designer program really helped me, I didn’t know it existed.