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

84 lines
1.7 KiB
Lua
Raw Normal View History

2022-04-21 16:44:46 +00:00
--
-- Message Queue
--
local mqueue = {}
2022-05-10 21:06:27 +00:00
---@alias TYPE integer
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
2022-05-10 21:06:27 +00:00
-- create a new message queue
2022-05-31 20:09:06 +00:00
function mqueue.new()
2022-04-21 16:44:46 +00:00
local queue = {}
2022-05-06 14:53:12 +00:00
local insert = table.insert
local remove = table.remove
2022-05-10 21:06:27 +00:00
---@class queue_item
2022-05-13 13:38:10 +00:00
---@field qtype TYPE
---@field message any
2022-04-21 16:44:46 +00:00
2022-05-13 16:23:01 +00:00
---@class queue_data
---@field key any
---@field val any
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
---@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
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 TYPE
---@param message string
2022-05-31 20:09:06 +00:00
local function _push(qtype, message)
2022-05-06 14:53:12 +00:00
insert(queue, { qtype = qtype, message = message })
2022-04-21 16:44:46 +00:00
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
2022-05-31 20:09:06 +00:00
function public.push_command(message)
_push(TYPE.COMMAND, message)
2022-04-21 16:44:46 +00:00
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
2022-05-31 20:09:06 +00:00
function public.push_data(key, value)
2022-05-01 19:35:07 +00:00
_push(TYPE.DATA, { key = key, val = value })
2022-04-27 16:21:10 +00:00
end
2022-05-10 21:06:27 +00:00
-- push a packet onto the queue
---@param packet scada_packet|modbus_packet|rplc_packet|coord_packet|capi_packet
2022-05-31 20:09:06 +00:00
function public.push_packet(packet)
2022-05-10 21:06:27 +00:00
_push(TYPE.PACKET, packet)
2022-04-27 16:21:10 +00:00
end
2022-05-10 21:06:27 +00:00
-- get an item off the queue
---@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)
2022-05-10 15:35:52 +00:00
else
2022-04-21 16:44:46 +00:00
return nil
end
end
2022-05-10 21:06:27 +00:00
return public
2022-04-21 16:44:46 +00:00
end
return mqueue