Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Manager
- local storage = {}
- function addStorage(sender, resource)
- print(("Attempting to add %s from %d"):format(resource, sender))
- if not storage[resource] then
- storage[resource] = {}
- end
- table.insert(storage[resource], sender)
- print(("Storage table is now: %s"):format(textutils.serialize(storage)))
- local message = {command = "ack"}
- rednet.send(sender, textutils.serialize(message))
- end
- function handleCommunications()
- local sender, message = rednet.receive()
- -- message { command = "storage", resource = "gravel|cobblestone|andesite|etc"}
- -- message { command = "request", resource = "gravel|cobblestone|andesite|etc", amount = 64}
- local actualMessage = textutils.unserialize(message)
- if actualMessage.command == "storage" then
- addStorage(sender, actualMessage.resource)
- elseif actualMessage.command == "request" then
- handleRequest(sender, actualMessage.resource, actualMessage.amount)
- elseif actualMessage.command == "bye" then
- handleGoodbye(sender)
- elseif actualMessage.command == "helo" then
- handleHello(sender)
- end
- end
- function handleGoodbye(sender)
- print(("Attempting goodbye for %d"):format(sender))
- for resource, list in pairs(storage) do
- for index, which in ipairs(list) do
- if which == sender then
- print(("Removing sender %d from %s"):format(sender, resource))
- table.remove(storage[resource], index)
- end
- end
- end
- local message = {command="ack"}
- rednet.send(sender, textutils.serialize(message))
- end
- function handleHello(sender)
- print(("Received hello from %d"):format(sender))
- local message = {command = "hello"}
- rednet.send(sender, textutils.serialize(message))
- end
- function handleRequest(sender, resource, amount)
- print(("Request received for %d %s from %d"):format(amount, resource, sender))
- if not storage[resource] then return end
- local resourceCount = table.maxn(storage[resource])
- if resourceCount > 0 then
- local perHost = math.ceil(amount / resourceCount)
- for _, host in ipairs(storage[resource]) do
- local message = {command = "request", amount = perHost}
- rednet.send(host, textutils.serialize(message))
- end
- end
- local message = {command = "ack"}
- rednet.send(sender, textutils.serialize(message))
- end
- function main()
- peripheral.find("modem", rednet.open)
- while true do
- handleCommunications()
- end
- end
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement