cc-mek-scada/scada-common/util.lua

568 lines
16 KiB
Lua
Raw Permalink Normal View History

2022-05-10 21:06:27 +00:00
--
-- Utility Functions
--
local cc_strings = require("cc.strings")
2024-06-01 04:50:19 +00:00
local const = require("scada-common.constants")
2023-10-08 16:47:51 +00:00
local math = math
local string = string
local table = table
local os = os
local getmetatable = getmetatable
local print = print
local tostring = tostring
local type = type
local t_concat = table.concat
local t_insert = table.insert
2023-11-28 00:32:52 +00:00
local t_pack = table.pack
2022-05-10 21:06:27 +00:00
---@class util
local util = {}
2023-07-31 00:46:04 +00:00
-- scada-common version
2024-08-26 01:29:20 +00:00
util.version = "1.4.3"
2023-07-31 00:46:04 +00:00
util.TICK_TIME_S = 0.05
util.TICK_TIME_MS = 50
2023-10-07 20:57:24 +00:00
--#region OPERATORS
2022-05-31 19:55:40 +00:00
-- trinary operator
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param cond boolean|nil condition
2022-05-31 19:55:40 +00:00
---@param a any return if true
---@param b any return if false
---@return any value
2022-05-31 20:09:06 +00:00
function util.trinary(cond, a, b)
2022-05-31 19:55:40 +00:00
if cond then return a else return b end
end
--#endregion
2023-10-07 20:57:24 +00:00
--#region PRINT
2022-04-05 21:28:19 +00:00
2023-10-08 16:47:51 +00:00
local p_time = "[%H:%M:%S] "
2022-04-05 21:28:19 +00:00
-- print
---@param message any
2023-10-07 20:57:24 +00:00
function util.print(message) term.write(tostring(message)) end
2022-04-05 21:28:19 +00:00
-- print line
---@param message any
2023-10-07 20:57:24 +00:00
function util.println(message) print(tostring(message)) end
2022-04-05 21:28:19 +00:00
2022-01-13 15:11:42 +00:00
-- timestamped print
---@param message any
2023-10-08 16:47:51 +00:00
function util.print_ts(message) term.write(os.date(p_time) .. tostring(message)) end
2022-01-13 15:11:42 +00:00
2022-04-05 21:28:19 +00:00
-- timestamped print line
---@param message any
2023-10-08 16:47:51 +00:00
function util.println_ts(message) print(os.date(p_time) .. tostring(message)) end
--#endregion
2023-10-07 20:57:24 +00:00
--#region STRING TOOLS
-- get a value as a string
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param val any
---@return string
2022-05-31 20:09:06 +00:00
function util.strval(val)
2023-10-14 03:53:15 +00:00
local t = type(val)
if t == "string" then return val end
-- this depends on Lua short-circuiting the or check for metatables (note: metatables won't have metatables)
2023-10-14 03:53:15 +00:00
if (t == "table" and (getmetatable(val) == nil or getmetatable(val).__tostring == nil)) or t == "function" then
return t_concat{"[", tostring(val), "]"}
2023-10-07 20:57:24 +00:00
else return tostring(val) end
end
-- tokenize a string by a separator<br>
-- does not behave exactly like C's strtok
---@param str string string to tokenize
---@param sep string separator to tokenize by
---@return table token_list
function util.strtok(str, sep)
local list = {}
for part in string.gmatch(str, "([^" .. sep .. "]+)") do t_insert(list, part) end
return list
end
2022-06-11 16:20:49 +00:00
-- repeat a space n times
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-06-11 16:20:49 +00:00
---@param n integer
---@return string
2023-10-07 20:57:24 +00:00
function util.spaces(n) return string.rep(" ", n) end
2022-06-11 16:20:49 +00:00
2022-08-16 15:22:06 +00:00
-- pad text to a minimum width
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-08-16 15:22:06 +00:00
---@param str string text
---@param n integer minimum width
---@return string
function util.pad(str, n)
local len = string.len(str)
local lpad = math.floor((n - len) / 2)
local rpad = (n - len) - lpad
return t_concat{util.spaces(lpad), str, util.spaces(rpad)}
2022-08-16 15:22:06 +00:00
end
-- trim leading and trailing whitespace
---@nodiscard
---@param s string text
---@return string
function util.trim(s)
local str = s:gsub("^%s*(.-)%s*$", "%1")
return str
end
-- wrap a string into a table of lines
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-06-08 22:48:20 +00:00
---@param str string
2024-07-23 03:44:34 +00:00
---@param limit integer line limit, must be greater than 0
2022-06-08 22:48:20 +00:00
---@return table lines
2024-07-23 03:44:34 +00:00
function util.strwrap(str, limit)
assert(limit > 0, "util.strwrap() limit not greater than 0")
return cc_strings.wrap(str, limit)
end
2022-06-08 22:48:20 +00:00
2024-07-27 16:34:01 +00:00
-- make sure a string is at least 'width' long
---@nodiscard
---@param str string
---@param width integer minimum width
---@return string string
function util.strminw(str, width) return cc_strings.ensure_width(str, width) end
-- concatenation with built-in to string
2023-02-21 15:31:05 +00:00
---@nodiscard
---@vararg any
---@return string
2022-05-31 20:09:06 +00:00
function util.concat(...)
2023-11-28 00:32:52 +00:00
local args, strings = t_pack(...), {}
for i = 1, args.n do strings[i] = util.strval(args[i]) end
return t_concat(strings)
end
2022-05-31 19:55:40 +00:00
-- alias
util.c = util.concat
-- sprintf implementation
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param format string
---@vararg any
2023-11-28 00:32:52 +00:00
function util.sprintf(format, ...) return string.format(format, ...) end
2023-05-05 17:55:14 +00:00
2023-02-21 15:31:05 +00:00
-- format a number string with commas as the thousands separator<br>
-- subtracts from spaces at the start if present for each comma used
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param num string number string
---@return string
function util.comma_format(num)
local formatted = num
local commas = 0
local i = 1
while i > 0 do
2023-10-14 03:48:30 +00:00
formatted, i = formatted:gsub("^(%s-%d+)(%d%d%d)", "%1,%2")
if i > 0 then commas = commas + 1 end
end
2023-10-14 03:48:30 +00:00
local _, num_spaces = formatted:gsub(" %s-", "")
local remove = math.min(num_spaces, commas)
formatted = string.sub(formatted, remove + 1)
return formatted
end
--#endregion
2023-10-07 20:57:24 +00:00
--#region MATH
2022-06-05 20:51:38 +00:00
2023-10-14 03:48:30 +00:00
-- is a value an integer
---@nodiscard
---@param x any value
---@return boolean is_integer
function util.is_int(x) return type(x) == "number" and x == math.floor(x) end
-- get the sign of a number
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param x number value
---@return integer sign (-1 for < 0, 1 otherwise)
2023-10-07 20:57:24 +00:00
function util.sign(x) return util.trinary(x < 0, -1, 1) end
2022-05-31 19:55:40 +00:00
-- round a number to an integer
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-31 19:55:40 +00:00
---@return integer rounded
2023-10-07 20:57:24 +00:00
function util.round(x) return math.floor(x + 0.5) end
2022-05-31 19:55:40 +00:00
-- get a new moving average object
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param length integer history length
function util.mov_avg(length)
local data = {}
local index = 1
2023-10-08 16:47:51 +00:00
local last_t = 0 ---@type number|nil
---@class moving_average
local public = {}
-- reset all to a given value, or clear all data if no value is given
---@param x number? value
function public.reset(x)
index = 1
data = {}
if x then
for _ = 1, length do t_insert(data, x) end
end
end
-- record a new value
---@param x number new value
---@param t number? optional last update time to prevent duplicated entries
function public.record(x, t)
2023-10-14 03:48:30 +00:00
if type(t) == "number" and last_t == t then return end
data[index] = x
last_t = t
index = index + 1
if index > length then index = 1 end
end
-- compute the moving average
2023-02-21 15:31:05 +00:00
---@nodiscard
---@return number average
function public.compute()
if #data == 0 then return 0 end
local sum = 0
for i = 1, #data do
sum = sum + data[i]
end
return sum / #data
end
return public
end
2023-10-07 20:57:24 +00:00
--#endregion
--#region TIME
2022-05-10 21:06:27 +00:00
-- current time
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-10 21:06:27 +00:00
---@return integer milliseconds
---@diagnostic disable-next-line: undefined-field
2023-10-14 03:48:30 +00:00
function util.time_ms() return os.epoch("local") end
2022-05-10 21:06:27 +00:00
-- current time
2023-02-21 15:31:05 +00:00
---@nodiscard
---@return number seconds
---@diagnostic disable-next-line: undefined-field
2023-10-14 03:48:30 +00:00
function util.time_s() return os.epoch("local") / 1000.0 end
2022-05-10 21:06:27 +00:00
-- current time
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-10 21:06:27 +00:00
---@return integer milliseconds
2023-02-21 15:31:05 +00:00
function util.time() return util.time_ms() end
--#endregion
2023-10-07 20:57:24 +00:00
--#region OS
-- OS pull event raw wrapper with types
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param target_event? string event to wait for
---@return os_event event, any param1, any param2, any param3, any param4, any param5
---@diagnostic disable-next-line: undefined-field
2023-10-08 16:47:51 +00:00
function util.pull_event(target_event) return os.pullEventRaw(target_event) end
-- OS queue event raw wrapper with types
---@param event os_event
---@param param1 any
---@param param2 any
---@param param3 any
---@param param4 any
---@param param5 any
function util.push_event(event, param1, param2, param3, param4, param5)
---@diagnostic disable-next-line: undefined-field
return os.queueEvent(event, param1, param2, param3, param4, param5)
end
-- start an OS timer
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param t number timer duration in seconds
---@return integer timer ID
---@diagnostic disable-next-line: undefined-field
2023-10-08 16:47:51 +00:00
function util.start_timer(t) return os.startTimer(t) end
-- cancel an OS timer
---@param timer integer timer ID
---@diagnostic disable-next-line: undefined-field
2023-10-08 16:47:51 +00:00
function util.cancel_timer(timer) os.cancelTimer(timer) end
--#endregion
2023-10-07 20:57:24 +00:00
--#region PARALLELIZATION
2024-03-05 22:12:12 +00:00
-- protected sleep call so we still are in charge of catching termination<br>
-- returns the result of pcall
---@param t number seconds
---@return boolean success, any result, any ...
2022-05-10 21:06:27 +00:00
--- EVENT_CONSUMER: this function consumes events
---@diagnostic disable-next-line: undefined-field
2024-03-05 22:12:12 +00:00
function util.psleep(t) return pcall(os.sleep, t) end
2023-02-21 15:31:05 +00:00
-- no-op to provide a brief pause (1 tick) to yield<br>
2022-05-10 21:06:27 +00:00
--- EVENT_CONSUMER: this function consumes events
2023-02-21 15:31:05 +00:00
function util.nop() util.psleep(0.05) end
-- attempt to maintain a minimum loop timing (duration of execution)<br>
-- note: will not yield for time periods less than 50ms
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-10 21:06:27 +00:00
---@param target_timing integer minimum amount of milliseconds to wait for
---@param last_update integer millisecond time of last update
---@return integer time_now
2022-07-06 03:48:01 +00:00
--- EVENT_CONSUMER: this function consumes events
2022-05-31 20:09:06 +00:00
function util.adaptive_delay(target_timing, last_update)
local sleep_for = target_timing - (util.time() - last_update)
-- only if >50ms since worker loops already yield 0.05s
2023-02-21 15:31:05 +00:00
if sleep_for >= 50 then util.psleep(sleep_for / 1000.0) end
return util.time()
end
--#endregion
2023-10-07 20:57:24 +00:00
--#region TABLE UTILITIES
2022-05-16 21:11:46 +00:00
2023-02-21 15:31:05 +00:00
-- delete elements from a table if the passed function returns false when passed a table element<br>
2022-05-16 21:11:46 +00:00
-- put briefly: deletes elements that return false, keeps elements that return true
---@param t table table to remove elements from
---@param f function should return false to delete an element when passed the element: f(elem) = true|false
---@param on_delete? function optional function to execute on deletion, passed the table element to be deleted as the parameter
2022-05-31 20:09:06 +00:00
function util.filter_table(t, f, on_delete)
2022-05-16 21:11:46 +00:00
local move_to = 1
for i = 1, #t do
local element = t[i]
if element ~= nil then
if f(element) then
if t[move_to] == nil then
t[move_to] = element
t[i] = nil
end
move_to = move_to + 1
else
if on_delete then on_delete(element) end
t[i] = nil
end
end
end
end
2022-05-18 18:30:48 +00:00
-- check if a table contains the provided element
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-18 18:30:48 +00:00
---@param t table table to check
---@param element any element to check for
2022-05-31 20:09:06 +00:00
function util.table_contains(t, element)
2022-05-18 18:30:48 +00:00
for i = 1, #t do
if t[i] == element then return true end
end
return false
end
2024-02-14 14:43:30 +00:00
-- count the length of a table, even if the values are not sequential or contain named keys
---@nodiscard
---@param t table
---@return integer length
function util.table_len(t)
local n = 0
for _, _ in pairs(t) do n = n + 1 end
return n
end
--#endregion
2024-06-01 04:50:19 +00:00
--#region MEKANISM MATH
2022-05-10 21:06:27 +00:00
2024-07-27 16:34:01 +00:00
-- convert Joules to FE (or RF)
2023-02-21 15:31:05 +00:00
---@nodiscard
---@param J number Joules
2024-07-27 16:34:01 +00:00
---@return number FE Forge Energy or Redstone Flux
function util.joules_to_fe_rf(J) return (J * 0.4) end
2024-07-27 16:34:01 +00:00
-- convert FE (or RF) to Joules
2023-02-21 15:31:05 +00:00
---@nodiscard
2024-07-27 16:34:01 +00:00
---@param FE number Forge Energy or Redstone Flux
---@return number J Joules
2024-07-27 16:34:01 +00:00
function util.fe_rf_to_joules(FE) return (FE * 2.5) end
2024-07-27 16:34:01 +00:00
-- format a power value into XXX.XX UNIT format<br>
-- example for FE: FE, kFE, MFE, GFE, TFE, PFE, EFE, ZFE
2023-02-21 15:31:05 +00:00
---@nodiscard
2024-07-27 16:34:01 +00:00
---@param e number energy value
---@param label string energy scale label
---@param combine_label? boolean if a label should be included in the string itself
---@param format? string format override
2024-07-27 16:34:01 +00:00
---@return string str, string unit
function util.power_format(e, label, combine_label, format)
2023-10-08 16:47:51 +00:00
local unit, value
2023-02-21 15:31:05 +00:00
if type(format) ~= "string" then format = "%.2f" end
2024-07-27 16:34:01 +00:00
if e < 1000.0 then
unit = ""
value = e
elseif e < 1000000.0 then
unit = "k"
value = e / 1000.0
elseif e < 1000000000.0 then
unit = "M"
value = e / 1000000.0
elseif e < 1000000000000.0 then
unit = "G"
value = e / 1000000000.0
elseif e < 1000000000000000.0 then
unit = "T"
value = e / 1000000000000.0
elseif e < 1000000000000000000.0 then
unit = "P"
value = e / 1000000000000000.0
elseif e < 1000000000000000000000.0 then
-- if you accomplish this please touch grass
unit = "E"
value = e / 1000000000000000000.0
else
2024-07-27 16:34:01 +00:00
-- how & why did you do this?
unit = "Z"
value = e / 1000000000000000000000.0
end
2024-07-27 16:34:01 +00:00
unit = unit .. label
if combine_label then
2024-07-27 16:34:01 +00:00
return util.sprintf(util.c(format, " %s"), value, unit), unit
else
return util.sprintf(format, value), unit
end
end
2022-05-10 21:06:27 +00:00
2024-06-01 04:50:19 +00:00
-- compute Mekanism's rotation rate for a turbine
---@nodiscard
---@param turbine turbinev_session_db turbine data
function util.turbine_rotation(turbine)
local build = turbine.build
local inner_vol = build.steam_cap / const.mek.TURBINE_GAS_PER_TANK
local disp_rate = (build.dispersers * const.mek.TURBINE_DISPERSER_FLOW) * inner_vol
local vent_rate = build.vents * const.mek.TURBINE_VENT_FLOW
local max_rate = math.min(disp_rate, vent_rate)
local flow = math.min(max_rate, turbine.tanks.steam.amount)
return (flow * (turbine.tanks.steam.amount / build.steam_cap)) / max_rate
end
--#endregion
2023-10-07 20:57:24 +00:00
--#region UTILITY CLASSES
-- WATCHDOG --
2022-04-05 21:28:19 +00:00
2023-02-21 15:31:05 +00:00
-- OS timer based watchdog<br>
-- triggers a timer event if not fed within 'timeout' seconds
---@nodiscard
2022-05-10 17:06:13 +00:00
---@param timeout number timeout duration
2022-05-31 20:09:06 +00:00
function util.new_watchdog(timeout)
2023-10-08 16:47:51 +00:00
local self = { timeout = timeout, wd_timer = util.start_timer(timeout) }
2022-01-13 15:11:42 +00:00
2022-05-10 17:06:13 +00:00
---@class watchdog
local public = {}
2023-02-21 15:31:05 +00:00
-- check if a timer is this watchdog
---@nodiscard
2023-10-08 16:47:51 +00:00
---@param timer number event timer ID
2023-02-21 15:31:05 +00:00
function public.is_timer(timer) return self.wd_timer == timer end
2022-05-10 15:35:52 +00:00
2022-05-10 17:06:13 +00:00
-- satiate the beast
2022-05-31 20:09:06 +00:00
function public.feed()
2023-10-08 16:47:51 +00:00
public.cancel()
self.wd_timer = util.start_timer(self.timeout)
2022-01-13 15:11:42 +00:00
end
2022-05-10 17:06:13 +00:00
-- cancel the watchdog
2022-05-31 20:09:06 +00:00
function public.cancel()
2023-10-08 16:47:51 +00:00
if self.wd_timer ~= nil then util.cancel_timer(self.wd_timer) end
2022-05-02 15:44:10 +00:00
end
2022-05-10 17:06:13 +00:00
return public
end
-- LOOP CLOCK --
2023-02-21 15:31:05 +00:00
-- OS timer based loop clock<br>
-- fires a timer event at the specified period, does not start at construct time
---@nodiscard
2022-05-10 17:06:13 +00:00
---@param period number clock period
2022-05-31 20:09:06 +00:00
function util.new_clock(period)
2023-10-08 16:47:51 +00:00
local self = { period = period, timer = nil }
2022-05-10 17:06:13 +00:00
---@class clock
local public = {}
2023-02-21 15:31:05 +00:00
-- check if a timer is this clock
---@nodiscard
2022-05-10 17:06:13 +00:00
---@param timer number timer event timer ID
2023-02-21 15:31:05 +00:00
function public.is_clock(timer) return self.timer == timer end
2022-05-10 17:06:13 +00:00
-- start the clock
2023-02-21 15:31:05 +00:00
function public.start() self.timer = util.start_timer(self.period) end
2022-05-10 17:06:13 +00:00
return public
2022-01-13 15:11:42 +00:00
end
-- FIELD VALIDATOR --
2023-02-21 15:31:05 +00:00
-- create a new type validator<br>
2022-06-05 19:09:02 +00:00
-- can execute sequential checks and check valid() to see if it is still valid
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-06-05 19:09:02 +00:00
function util.new_validator()
local valid = true
---@class validator
local public = {}
2023-10-14 03:48:30 +00:00
function public.assert_type_bool(value) valid = valid and type(value) == "boolean" end
function public.assert_type_num(value) valid = valid and type(value) == "number" end
2022-06-05 20:54:34 +00:00
function public.assert_type_int(value) valid = valid and util.is_int(value) end
2023-10-14 03:48:30 +00:00
function public.assert_type_str(value) valid = valid and type(value) == "string" end
function public.assert_type_table(value) valid = valid and type(value) == "table" end
2022-06-05 19:09:02 +00:00
function public.assert(check) valid = valid and (check == true) end
2022-06-05 19:09:02 +00:00
function public.assert_eq(check, expect) valid = valid and check == expect end
function public.assert_min(check, min) valid = valid and check >= min end
function public.assert_min_ex(check, min) valid = valid and check > min end
function public.assert_max(check, max) valid = valid and check <= max end
function public.assert_max_ex(check, max) valid = valid and check < max end
function public.assert_range(check, min, max) valid = valid and check >= min and check <= max end
function public.assert_range_ex(check, min, max) valid = valid and check > min and check < max end
2023-10-07 20:57:24 +00:00
function public.assert_channel(channel) valid = valid and util.is_int(channel) and channel >= 0 and channel <= 65535 end
2022-06-05 19:09:02 +00:00
2023-02-21 15:31:05 +00:00
-- check if all assertions passed successfully
---@nodiscard
2022-06-05 19:09:02 +00:00
function public.valid() return valid end
return public
end
--#endregion
return util