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

79 lines
1.7 KiB
Lua
Raw Permalink Normal View History

2022-04-21 16:44:46 +00:00
--
-- Message Queue
--
local mqueue = {}
---@class queue_item
---@field qtype MQ_TYPE
---@field message any
---@class queue_data
---@field key any
---@field val any
2023-02-21 15:31:05 +00:00
---@enum MQ_TYPE
local TYPE = {
2022-04-21 16:44:46 +00:00
COMMAND = 0,
2022-04-27 16:21:10 +00:00
DATA = 1,
PACKET = 2
2022-04-21 16:44:46 +00:00
}
mqueue.TYPE = TYPE
local insert = table.insert
local remove = table.remove
2022-05-10 21:06:27 +00:00
-- create a new message queue
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-31 20:09:06 +00:00
function mqueue.new()
2022-04-21 16:44:46 +00:00
local queue = {}
2022-05-10 21:06:27 +00:00
---@class mqueue
local public = {}
2022-04-27 16:21:10 +00:00
2022-05-10 21:06:27 +00:00
-- get queue length
2022-05-31 20:09:06 +00:00
function public.length() return #queue end
2022-05-10 15:35:52 +00:00
2022-05-10 21:06:27 +00:00
-- check if queue is empty
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-10 21:06:27 +00:00
---@return boolean is_empty
2022-05-31 20:09:06 +00:00
function public.empty() return #queue == 0 end
2022-05-10 21:06:27 +00:00
-- check if queue has contents
2023-02-21 15:31:05 +00:00
---@nodiscard
---@return boolean has_contents
2022-05-31 20:09:06 +00:00
function public.ready() return #queue ~= 0 end
2022-05-10 21:06:27 +00:00
-- push a new item onto the queue
---@param qtype MQ_TYPE
---@param message any
local function _push(qtype, message) insert(queue, { qtype = qtype, message = message }) end
2022-05-10 15:35:52 +00:00
2022-05-10 21:06:27 +00:00
-- push a command onto the queue
---@param message any
function public.push_command(message) _push(TYPE.COMMAND, message) end
2022-04-27 16:21:10 +00:00
2022-05-10 21:06:27 +00:00
-- push data onto the queue
---@param key any
---@param value any
function public.push_data(key, value) _push(TYPE.DATA, { key = key, val = value }) end
2022-04-27 16:21:10 +00:00
2022-05-10 21:06:27 +00:00
-- push a packet onto the queue
---@param packet packet|frame
function public.push_packet(packet) _push(TYPE.PACKET, packet) end
2022-04-27 16:21:10 +00:00
2022-05-10 21:06:27 +00:00
-- get an item off the queue
2023-02-21 15:31:05 +00:00
---@nodiscard
2022-05-10 21:06:27 +00:00
---@return queue_item|nil
2022-05-31 20:09:06 +00:00
function public.pop()
2022-04-21 16:44:46 +00:00
if #queue > 0 then
2022-05-06 14:53:12 +00:00
return remove(queue, 1)
else return nil end
2022-04-21 16:44:46 +00:00
end
2022-05-10 21:06:27 +00:00
return public
2022-04-21 16:44:46 +00:00
end
return mqueue