Hi Guys,
I’m working on a script to get the electricity prices from an API and write those prices to a group address. So far, everything works fine except when the value is negative. For example, -0.00036. In this case, the 2-byte object gets 0 as a value. How can I solve this?
Thanks in advance.
I’m working on a script to get the electricity prices from an API and write those prices to a group address. So far, everything works fine except when the value is negative. For example, -0.00036. In this case, the 2-byte object gets 0 as a value. How can I solve this?
Thanks in advance.
Code:
local http = require('ssl.https')
local json = require('json')
local date = os.date('*t') -- get today's date
local year = tostring(date.year)
local month = string.format('%02d', date.month)
local day = string.format('%02d', date.day)
local area = 'NO3' -- specify area
local url = string.format('https://www.hvakosterstrommen.no/api/v1/prices/%s/%s-%s_%s.json', year, month, day, area)
log('Fetching data from URL:', url)
local body, code, headers, status = http.request(url)
log('HTTP response code:', code)
if code == 200 then
--log('Data retrieved successfully')
--log('Response body:', body)
local data = json.decode(body)
log(data)
local min_price = math.huge -- start with a very high value for minimum
local max_price = -math.huge -- start with a very low value for maximum
local total_price = 0
local count = 0
for i, item in ipairs(data) do
local start_hour = string.sub(item.time_start, 12, 13)
local end_hour = string.sub(item.time_end, 12, 13)
local price = item.NOK_per_kWh
-- Calculate min, max, and total prices for average
if price < min_price then min_price = price end
if price > max_price then max_price = price end
total_price = total_price + price
count = count + 1
local time_range = string.format("%s TIL %s", start_hour, end_hour)
-- log("Time Range:", time_range)
-- log("Price:", price)
local address = '35/0/' .. i -- Example: '35/0/1', '35/0/2', etc.
grp.create({name = time_range, address = address, datatype = 09})
grp.write(time_range, price )
-- Small delay between each write
os.sleep(0.)
end
local average_price = total_price / count
grp.write('35/1/0', min_price )
grp.write('35/1/1', max_price )
grp.write('35/1/2', average_price)
else
log('Error fetching data:', status)
end