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

86 lines
2.7 KiB
Lua
Raw Normal View History

2022-06-08 18:47:45 +00:00
--
-- Timer Callback Dispatcher
--
2022-10-21 19:15:56 +00:00
local log = require("scada-common.log")
local util = require("scada-common.util")
2022-06-08 18:47:45 +00:00
local tcallbackdsp = {}
local registry = {}
-- request a function to be called after the specified time
---@param time number seconds
---@param f function callback function
function tcallbackdsp.dispatch(time, f)
local timer = util.start_timer(time)
registry[timer] = {
callback = f,
duration = time,
expiry = time + util.time_s()
}
2022-06-08 18:47:45 +00:00
end
2022-10-21 19:15:56 +00:00
-- request a function to be called after the specified time, aborting any registered instances of that function reference
---@param time number seconds
---@param f function callback function
function tcallbackdsp.dispatch_unique(time, f)
-- cancel if already registered
2022-10-21 19:15:56 +00:00
for timer, entry in pairs(registry) do
if entry.callback == f then
-- found an instance of this function reference, abort it
log.debug(util.c("TCD: aborting duplicate timer callback [timer: ", timer, ", ", f, "]"))
2022-10-21 19:15:56 +00:00
-- cancel event and remove from registry (even if it fires it won't call)
util.cancel_timer(timer)
2022-10-21 19:15:56 +00:00
registry[timer] = nil
end
end
local timer = util.start_timer(time)
registry[timer] = {
callback = f,
duration = time,
expiry = time + util.time_s()
}
2022-10-21 19:15:56 +00:00
end
-- abort a requested callback
---@param f function callback function
function tcallbackdsp.abort(f)
for timer, entry in pairs(registry) do
if entry.callback == f then
-- cancel event and remove from registry (even if it fires it won't call)
util.cancel_timer(timer)
registry[timer] = nil
end
end
end
2022-06-08 18:47:45 +00:00
-- lookup a timer event and execute the callback if found
---@param event integer timer event timer ID
function tcallbackdsp.handle(event)
if registry[event] ~= nil then
local callback = registry[event].callback
-- clear first so that dispatch_unique call from inside callback won't throw a debug message
2022-06-08 18:47:45 +00:00
registry[event] = nil
callback()
end
end
2023-02-21 15:31:05 +00:00
-- identify any overdo callbacks<br>
-- prints to log debug output
function tcallbackdsp.diagnostics()
for timer, entry in pairs(registry) do
if entry.expiry < util.time_s() then
local overtime = util.time_s() - entry.expiry
log.debug(util.c("TCD: unserviced timer ", timer, " for callback ", entry.callback, " is at least ", overtime, "s late"))
else
local time = entry.expiry - util.time_s()
log.debug(util.c("TCD: pending timer ", timer, " for callback ", entry.callback, " (call after ", entry.duration, "s, expires ", time, ")"))
end
2022-06-08 18:47:45 +00:00
end
end
return tcallbackdsp