Advertisement
osmarks

BundleModem

Aug 7th, 2019
657
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.99 KB | None | 0 0
  1. local a=http.get"https://pastebin.com/raw/QTwgLZMA"local b=fs.open("bundlenet","w")b.write(a.readAll())a.close()b.close()
  2.  
  3. local bnet = require "/bundlenet"
  4. local m = peripheral.find "modem"
  5.  
  6. local function compact_serialize(x)
  7.     local t = type(x)
  8.     if t == "number" then
  9.         return tostring(x)
  10.     elseif t == "string" then
  11.         return textutils.serialise(x)
  12.     elseif t == "table" then
  13.         local out = "{"
  14.         for k, v in pairs(x) do
  15.             out = out .. string.format("[%s]=%s,", compact_serialize(k), compact_serialize(v))
  16.         end
  17.         return out .. "}"
  18.     elseif t == "boolean" then
  19.         return tostring(x)
  20.     else
  21.         error("Unsupported type " .. t)
  22.     end
  23. end
  24.  
  25. local commands = {
  26.     open = function(channel)
  27.         m.open(channel)
  28.         return true
  29.     end,
  30.     transmit = function(channel, reply_channel, message)
  31.         m.transmit(channel, reply_channel, message)
  32.         return true
  33.     end,
  34.     close = function(channel)
  35.         m.close(channel)
  36.         return true
  37.     end,
  38.     listen = function()
  39.         local _, _, c, rc, msg, dist = os.pullEvent "modem_message"
  40.         return { channel = c, reply_channel = rc, message = msg, distance = dist }
  41.     end
  42. }
  43.  
  44. if m then
  45.     print "Configured as modem end."
  46.     while true do
  47.         local msg = bnet.receive()
  48.         local data = textutils.unserialize(msg)
  49.         if data then
  50.             local command = table.remove(data, 1)
  51.             if commands[command] then
  52.                 local ok, res = pcall(commands[command], unpack(data))
  53.                 local type = "result"
  54.                 if not ok then type = "error" end
  55.                 sleep(0.1)
  56.                 bnet.send(compact_serialize { type, res })
  57.             else
  58.                 sleep(0.1)
  59.                 bnet.send(compact_serialize { "error", "command not found" })
  60.             end
  61.         end
  62.     end
  63. else
  64.     print "No modem found. Acting as BundleModem remote."
  65.     return function(...)
  66.         bnet.send(compact_serialize {...})
  67.         sleep(0.3)
  68.         local result = textutils.unserialize(bnet.receive())
  69.         if result[1] == "result" then return result[2]
  70.         elseif result[2] == "error" then error(result[2]) end
  71.         return
  72.     end
  73. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement