From aff166e27d22ab0d80e773fe4f4b46db1b11e813 Mon Sep 17 00:00:00 2001 From: Mikayla Fischler Date: Wed, 27 Apr 2022 19:06:01 -0400 Subject: [PATCH] added util adaptive_delay to replace repeated code --- reactor-plc/threads.lua | 16 ++++------------ rtu/threads.lua | 8 ++------ scada-common/util.lua | 10 ++++++++++ 3 files changed, 16 insertions(+), 18 deletions(-) diff --git a/reactor-plc/threads.lua b/reactor-plc/threads.lua index 5cc80bc..a9b95d7 100644 --- a/reactor-plc/threads.lua +++ b/reactor-plc/threads.lua @@ -287,12 +287,8 @@ function thread__iss(smem) break end - -- delay before next check, only if >50ms since we did already yield - local sleep_for = ISS_SLEEP - (util.time() - last_update) - last_update = util.time() - if sleep_for >= 50 then - psleep(sleep_for / 1000.0) - end + -- delay before next check + last_update = util.adaptive_delay(ISS_SLEEP, last_update) end end @@ -344,12 +340,8 @@ function thread__comms(smem) break end - -- delay before next check, only if >50ms since we did already yield - local sleep_for = COMMS_SLEEP - (util.time() - last_update) - last_update = util.time() - if sleep_for >= 50 then - psleep(sleep_for / 1000.0) - end + -- delay before next check + last_update = util.adaptive_delay(COMMS_SLEEP, last_update) end end diff --git a/rtu/threads.lua b/rtu/threads.lua index d736ee1..fece382 100644 --- a/rtu/threads.lua +++ b/rtu/threads.lua @@ -144,12 +144,8 @@ function thread__comms(smem) break end - -- delay before next check, only if >50ms since we did already yield - local sleep_for = COMMS_SLEEP - (util.time() - last_update) - last_update = util.time() - if sleep_for >= 50 then - psleep(sleep_for / 1000.0) - end + -- delay before next check + last_update = util.adaptive_delay(COMMS_SLEEP, last_update) end end diff --git a/scada-common/util.lua b/scada-common/util.lua index 69bc7f1..36761fd 100644 --- a/scada-common/util.lua +++ b/scada-common/util.lua @@ -50,6 +50,16 @@ function nop() psleep(0.05) end +-- attempt to maintain a minimum loop timing (duration of execution) +function adaptive_delay(target_timing, last_update) + local sleep_for = target_timing - (time() - last_update) + -- only if >50ms since worker loops already yield 0.05s + if sleep_for >= 50 then + psleep(sleep_for / 1000.0) + end + return time() +end + -- WATCHDOG -- -- ComputerCraft OS Timer based Watchdog