Advertisement
klindley

processor

May 10th, 2023 (edited)
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.88 KB | None | 0 0
  1. -- Processor Host
  2. local keepAlive = true
  3. local processor;
  4. local resource;
  5. local manager;
  6. local PROCESS_MINIMUM = 64
  7.  
  8. function doHello()
  9.   print("Sending Hello")
  10.  
  11.   local message = {command="helo"}
  12.   rednet.broadcast(textutils.serialize(message))
  13. end
  14.  
  15. function doRequest(amount)
  16.   print(("Requesting %s: %d"):format(resource, amount))
  17.  
  18.   local message = {command = "request", resource = resource, amount = amount}
  19.   rednet.send(manager, textutils.serialize(message))
  20. end
  21.  
  22. function handleCommunications()
  23.   local sender, message = rednet.receive()
  24.   print(("Received message from %d: %s"):format(sender, message))
  25.  
  26.   local actualMessage = textutils.unserialize(message)
  27.  
  28.   if actualMessage.command == "request" then
  29.     handleRequest(amount)
  30.   elseif actualMessage.command == "hello" then
  31.     handleHello(sender)
  32.   end
  33. end
  34.  
  35. function handleHello(sender)
  36.   print(("Received hello from %d"):format(sender))
  37.  
  38.   manager = sender
  39.   local message = {command = "ack"}
  40.   rednet.send(manager, textutils.serialize(message))
  41. end
  42.  
  43. function handleTerminate()
  44.   os.pullEventRaw("terminate")
  45.   local message = {command="bye"}
  46.   rednet.send(manager, textutils.serialize(message))
  47.   keepAlive = false
  48. end
  49.  
  50. function processInventory()
  51.   local inventory = processor.list()
  52.  
  53.   local count = 0
  54.   for slot, item in pairs(inventory) do
  55.     if slot then count = count + item.count end
  56.   end
  57.  
  58.   if count < PROCESS_MINIMUM then
  59.     doRequest(PROCESS_MINIMUM - count)
  60.   end
  61. end
  62.  
  63. function main(...)
  64.   resource = ...
  65.   if not resource then
  66.     print("Please specify a requirement: processor cobblestone")
  67.     return
  68.   end
  69.  
  70.   peripheral.find("modem", rednet.open)
  71.   processor = peripheral.wrap("top")
  72.  
  73.   doHello()
  74.   handleCommunications()
  75.  
  76.   while keepAlive do
  77.     parallel.waitForAny(processInventory, handleCommunications, handleTerminate)
  78.  
  79.     os.sleep(10)
  80.   end
  81. end
  82.  
  83. main(...)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement