Advertisement
jhnphm

InvSensor

Feb 24th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.15 KB | None | 0 0
  1. -- load the API
  2. os.loadAPI("ocs/apis/sensor")
  3. -- wrap the sensor
  4. local invSensor = sensor.wrap("left")
  5. modem = peripheral.wrap("top")
  6. modem.setDefaultChannel(1)
  7. modem.setListening(1,true)
  8. local inBounds = function(position)
  9.     if position.X <= 4 and position.X >= -4 and
  10.     position.Z <= 3 and position.Z >= -1 and
  11.     position.Y <= -1 and position.Y >= -4 then
  12. return true
  13. else
  14. return false
  15. end
  16. end
  17.  
  18. local convName = function(name)
  19.     name = name:lower()
  20.     name = name:gsub(" ", "_")
  21.     name = name:gsub('%(', "")
  22.     name = name:gsub('%)', "")
  23.     return name
  24. end
  25.  
  26. local getInventory = function()
  27.     local targets = invSensor.getTargets()
  28.     local inventory={}
  29.     for k,v in pairs(targets) do
  30.         local position = v.Position
  31.         if inBounds(position) then
  32.             local details = invSensor.getTargetDetails(k)
  33.             for i,v in pairs(details.Slots) do
  34.         if v.Name == "" then
  35.             name = v.RawName
  36.             else
  37.                 name = convName(v.Name)
  38.         end
  39.                 if name == "empty" then
  40.                     name = "_"
  41.                     if inventory[name] == nil then
  42.                         inventory[name] = 0
  43.                     end
  44.                     inventory[name] = inventory[name] + 64
  45.         else
  46.                     if inventory[name] == nil then
  47.                         inventory[name] = 0
  48.                     end
  49.                     inventory[name] = inventory[name] + v.Size
  50.                 end
  51.             end
  52.         end
  53.     end
  54.     return inventory
  55. end
  56.  
  57. local netListen = function()
  58.     local msg = {Command = nil, Payload = nil}
  59.     local id
  60.     while true do
  61.         local event,side,id,channel,srmsg = os.pullEvent("lan_message")
  62.         local msg = textutils.unserialize(srmsg)
  63.         if type(msg) == "table" then
  64.             print(msg.Command)
  65.             if msg.Command == "invDisplay.reportReq" then
  66.                 local storage = getInventory()
  67.                 local reply = {Command = "invSensor.report",Payload = {Inventory = storage}}
  68.                 reply = textutils.serialize(reply)
  69.                 modem.send(reply)
  70.             end
  71.         end
  72.     end
  73. end
  74.  
  75.  
  76. netListen()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement