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
mqueue.new = function ()
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
public.length = function () 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
public.empty = function () return #queue == 0 end
-- check if queue has contents
public.ready = function () return #queue ~= 0 end
-- push a new item onto the queue
---@param qtype TYPE
---@param message string
2022-04-21 16:44:46 +00:00
local _push = function (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
public.push_command = function (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
public.push_data = function (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
public.push_packet = function (packet)
_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
public.pop = function ()
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