I am so glad I no longer need to do such type gymnastics. In jruby:
rule "solaredge.selfconsumption" do
changed SolarEdge_Live_Consumption
run do
self_consumption = [SolarEdge_Live_Production - SolarEdge_Live_Consumption, 0].max | 'kW'
SolarEdge_Live_Self_Consumption.update(self_consumption)
logger.info("self consumption: #{self_consumption}")
end
end
Basically you just use the item name. It is automatically inferred that they’re a numeric type and you can perform arithmetic as if they’re a number, but you can also treat them like a first class openhab items, with so many capabilities, such as:
-
SolarEdge_Live_Self_Consumption.meta['namespace']
to access its metadata, -
SolarEdge_Live_Self_Consumption.persist
to tell it to persist to the database, -
SolarEdge_Live_Self_Consumption.average_since(24.hours, :influxdb)
to get the persistence average data, -
SolarEdge_Live_Self_Consumption.update '12kW'
to update it with a string with UoM, and many more.
Note if your Production is less than Consumption, your code will give you a negative self consumption. I’m not sure that’s what you wanted? My code above will set the self consumption to zero in this case.
A bit of note if you’re not familiar with ruby:
self_consumption.zero?
is just a preferred way of writing self_consumption == 0
or self_consumption == '0 W'
. You can use any of the 3 variations.
[x, y, z]
is an array, in this case [SolarEdge_Live_Production - SolarEdge_Live_Consumption, 0]
is an array containing two elements: the calculation result and zero. Then you call [array].max
to get the max of the elements. It’s the same as the traditional way of doing max(x, y) in other languages.