1amw31rd

ComputerCraft - Sorter

May 31st, 2013
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 7.74 KB | None | 0 0
  1. -- Load Tools API
  2. write("Loading Tools API... ")
  3. if os.loadAPI("tools") then print("Success.") else print("Failed.") return end
  4.  
  5. -- Get sorter ID
  6. local sID = os.getComputerID()
  7. local sLabel = os.getComputerLabel()
  8.  
  9. -- Get the user computer ID
  10. local userID = tools.gui.load("Getting user computer", "return tonumber(http.queueFriendlyRequest(\"http://localhost/storage.php?func=getUserComputer\", nil, true))")
  11. if not userID then return end
  12.  
  13. -- Get the sorter peripheral
  14. local sorter = tools.gui.load("Getting sorter", "return peripheral.find(\"interactiveSorter\")")--"for n,side in ipairs(rs.getSides()) do if peripheral.getType(side) == \"interactiveSorter\" then return peripheral.wrap(side) end end")
  15. if not sorter then return end
  16.  
  17. -- Register this sorter in the database
  18. local success = tools.gui.load("Initializing", "return http.queueFriendlyRequest(\"http://localhost/storage.php?func=initSorter\",\"sID="..sID.."\", true)", true)
  19. if not success then return end
  20.  
  21. -- Get this sorter's facing direction
  22. local function getSorterDirection()
  23.     local cursorX, cursorY = term.getCursorPos()
  24.     write("Getting direction... ")
  25.     local d = tonumber(http.queueFriendlyRequest("http://localhost/storage.php?func=getSorterDirection&sID="..sID, nil, true))
  26.     if d==nil then
  27.         print("Failed.")
  28.         return nil
  29.     elseif d>=0 and d<4 then
  30.         print("Success.")
  31.         return d
  32.     else
  33.         term.clearLine()
  34.         term.setCursorPos(cursorX, cursorY)
  35.         write("Please enter sorter direction: ")
  36.         local input = read()
  37.         cursorX, cursorY = term.getCursorPos()
  38.         cursorY = cursorY-1
  39.         term.setCursorPos(cursorX, cursorY)
  40.         term.clearLine()
  41.         write("Setting direction... ")
  42.         if tonumber(input) and tonumber(input)>=0 and tonumber(input)<4 then
  43.             input = tonumber(input)
  44.         elseif tonumber(tools.directions[input]) then
  45.             input = tonumber(tools.directions[input])
  46.         else
  47.             print("Bad direction.")
  48.             return nil
  49.         end
  50.         local response = http.queueFriendlyRequest("http://localhost/storage.php?func=setSorterDirection", "&sID="..sID.."&dir="..input, true)
  51.         if response==nil then
  52.             print("Failed.")
  53.             return nil
  54.         else
  55.             print("Success.")
  56.             return input
  57.         end
  58.     end
  59. end
  60. local direction = getSorterDirection()
  61. if not direction then return end
  62.  
  63. local chestInfo = {
  64.     ["output"] = tools.directions.toSorter("up"),
  65.     ["next"] = tools.directions.toSorter(direction),
  66.     ["back"] = tools.directions.toSorter(tools.directions.rotate(direction, -2)),
  67.     ["chest1"] = tools.directions.toSorter(tools.directions.rotate(direction, -1)),
  68.     ["chest2"] = tools.directions.toSorter(tools.directions.rotate(direction, 1)),
  69. }
  70.  
  71. -- Set this sorter's chest slot counts
  72. local success = tools.gui.load("Setting slots", "return http.queueFriendlyRequest(\"http://localhost/storage.php?func=setChestSizes\",\"sID="..sID.."&chest1="..(sorter.numSlots(chestInfo["chest1"]) or -1).."&chest2="..(sorter.numSlots(chestInfo["chest2"]) or -1).."\", true)", true)
  73. if not success then return end
  74.  
  75. -- Reset screen
  76. os.queueFriendlySleep(1)
  77. local _, cursorY = term.getCursorPos()
  78. for i=1,6,1 do
  79.     term.setCursorPos(1, cursorY-i)
  80.     term.clearLine()
  81. end
  82.  
  83. -- Check if items are already in sorter
  84. if sorter.getItem()~=nil then
  85.     local id, amount = sorter.getItem()
  86.     os.queueEvent("isort_item", id, amount)
  87. end
  88.  
  89. -- Functions
  90. local function sendErrorToUser(message)
  91.     if userID == nil then
  92.         print("ERROR: "..message.."; cannot send")
  93.         return
  94.     end
  95.     print("ERROR: "..message.."; sending to " .. userID)
  96.     rednet.send(userID, "ERROR:" .. message)
  97. end
  98. local function extract(direction, id, outputDirection, amount)
  99.     local loops = 0
  100.     while amount > 0 do
  101.         amount = amount - sorter.extract(direction, id, outputDirection, amount)
  102.         loops = loops + 1
  103.        
  104.         if loops > 20 then
  105.             return false
  106.         end
  107.     end
  108.    
  109.     return true
  110. end
  111. local function waitForNextSorterEmpty(extractingFromChest)
  112.     local itemsInNextSorter = sorter.list(chestInfo["next"])
  113.     while itemsInNextSorter ~= nil and next(itemsInNextSorter) ~= nil do
  114.         if sorter.getItem()==nil and not extractingFromChest then
  115.             break
  116.         end
  117.         os.queueFriendlySleep(0.05)
  118.         itemsInNextSorter = sorter.list(chestInfo["next"])
  119.     end
  120. end
  121.  
  122. -- Message loop
  123. print("Commands: Q to quit, C to clear, U to update")
  124. while true do
  125.     local event, a, b = os.pullEvent()
  126.    
  127.     if event=="char" then
  128.         if a=="q" then
  129.             return
  130.         elseif a=="c" then
  131.             tools.gui.reset()
  132.         elseif a=="u" then
  133.             shell.run("downloader tools")
  134.             shell.run("downloader sorter")
  135.             os.reboot()
  136.         end
  137.     elseif event=="isort_item" then
  138.         local command = string.parse(http.queueFriendlyRequest("http://localhost/storage.php?func=recieveItem", "sID="..sID.."&iID="..a.."&amt="..b, true), ",")
  139.         if command==nil then
  140.             sendErrorToUser("recieveItem("..sID..", "..id..", "..amount..") A returned nil")
  141.         else
  142.             for i=1,table.getn(command),1 do
  143.                 if command[i]=="SENDNEXT" then
  144.                     waitForNextSorterEmpty(false)
  145.                     sorter.sort(chestInfo["next"])
  146.                     break
  147.                 else
  148.                     local subCommand = string.parse(command[i], ">")
  149.                     if tonumber(subCommand[1])~=nil and tonumber(subCommand[2])~=nil then
  150.                         sorter.sort(chestInfo["chest"..subCommand[2]], tonumber(subCommand[1]))
  151.                     else
  152.                         sendErrorToUser("recieveItem("..sID..", "..id..", "..amount..") returned bad command")
  153.                     end
  154.                 end
  155.             end
  156.         end
  157.     elseif event=="redstone" and not string.startsWith(sLabel, "notfirst") then
  158.         while rs.getInput("front") do
  159.             local items=sorter.list(chestInfo["back"])
  160.             local id, amount = next(items)
  161.             id = tonumber(id)
  162.             amount = tonumber(amount)
  163.             if id~=nil and amount~=nil then
  164.                 local itemInfo = string.parse(http.queueFriendlyRequest("http://localhost/storage.php?func=getStackSizeAndCatigoryByID&iID="..id, nil, true), ",") -- [1]=stacksize, [2]=catigory
  165.                 if itemInfo==nil or tonumber(itemInfo[1])==nil or itemInfo[2]==nil then
  166.                     sendErrorToUser("Item info request returned nil")
  167.                     sorter.extract(chestInfo["back"], id, chestInfo["output"], amount)
  168.                 elseif itemInfo[2]==sLabel then
  169.                     itemInfo[1] = tonumber(itemInfo[1])
  170.                     if amount>itemInfo[1] then amount = itemInfo[1] end
  171.                     local command = string.parse(http.queueFriendlyRequest("http://localhost/storage.php?func=recieveItem", "sID="..sID.."&iID="..id.."&amt="..amount, true), ",")
  172.                     if command==nil then
  173.                         sendErrorToUser("recieveItem("..sID..", "..id..", "..amount..") B returned nil")
  174.                     else
  175.                         for i=1,table.getn(command),1 do
  176.                             if command[i]=="SENDNEXT" then
  177.                                 waitForNextSorterEmpty(true)
  178.                                 amount = amount - sorter.extract(chestInfo["back"], id, chestInfo["next"], amount)
  179.                                 if amount==0 then break end
  180.                             else
  181.                                 local subCommand = string.parse(command[i], ">")
  182.                                 if tonumber(subCommand[1])~=nil and tonumber(subCommand[2])~=nil then
  183.                                     amount = amount - sorter.extract(chestInfo["back"], id, chestInfo["chest"..subCommand[2]], tonumber(subCommand[1]))
  184.                                 else
  185.                                     sendErrorToUser("recieveItem("..sID..", "..id..", "..amount..") returned bad command")
  186.                                 end
  187.                             end
  188.                         end
  189.                     end
  190.                 end
  191.             end
  192.         end
  193.     elseif event=="rednet_message" then --This should be sent by the user's computer, with a command set from the database
  194.         if b=="all_sorters_update" then
  195.             shell.run("downloader tools")
  196.             shell.run("downloader sorter")
  197.             os.reboot()
  198.         end
  199.        
  200.         local command = string.parse(b, " ")
  201.         if command==nil then
  202.             sendErrorToUser("Pull request is nil")
  203.         elseif command[1]=="PULL" then
  204.             if tonumber(command[3]) ~= nil and tonumber(command[4]) ~= nil and tonumber(command[5]) ~= nil then
  205.                 if not extract(chestInfo["chest"..tonumber(command[3])], tonumber(command[4]), chestInfo["output"], tonumber(command[5])) then
  206.                     sendErrorToUser("Chest extraction failed")
  207.                 end
  208.             else
  209.                 sendErrorToUser("Bad pull request")
  210.             end
  211.         end
  212.     end
  213. end
Add Comment
Please, Sign In to add comment