Advertisement
osmarks

ModSys

Jun 25th, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.83 KB | None | 0 0
  1. local o = peripheral.find "monitor"
  2.  
  3. o.setTextScale(0.5)
  4.  
  5. term.redirect(o)
  6.  
  7. local function compact_serialize(x)
  8.     local t = type(x)
  9.     if t == "number" then
  10.         return tostring(x)
  11.     elseif t == "string" then
  12.         return textutils.serialise(x)
  13.     elseif t == "table" then
  14.         local out = "{ "
  15.         for k, v in pairs(x) do
  16.             out = out .. string.format("[%s]=%s, ", compact_serialize(k), compact_serialize(v))
  17.         end
  18.         return out .. "}"
  19.     elseif t == "boolean" then
  20.         return tostring(x)
  21.     else
  22.         error("Unsupported type " .. t)
  23.     end
  24. end
  25.  
  26. local function safe_serialize(m)
  27.     local ok, res = pcall(compact_serialize, m)
  28.     if ok then return res
  29.     else return ("[UNSERIALIZABLE %s: %s]"):format(tostring(m), res) end
  30. end
  31.  
  32. local function tostring_with_default(x)
  33.     if not x then return "[N/A]"
  34.     else return tostring(x) end
  35. end
  36.  
  37. local modems = { peripheral.find("modem", function(n, o) return n:match "modem_" and o.isWireless() end) }
  38. local integs = { peripheral.find "redstone_integrator" }
  39.  
  40. print "Initializing modems..."
  41.  
  42. for ix, m in pairs(modems) do
  43.     m.closeAll()
  44.     for i = 0, 127 do
  45.         m.open((128 * (ix - 1)) + i)
  46.     end
  47.     sleep()
  48. end
  49.  
  50. local function set_power(id, mode)
  51.     local i = integs[id]
  52.     i.setOutput("top", mode)
  53.     i.setOutput("bottom", mode)
  54. end
  55.  
  56. for i in pairs(integs) do
  57.     set_power(i, true)
  58. end
  59.  
  60. local divisor = 65536 / #integs
  61.  
  62. print "Done!"
  63.  
  64. local timers = {}
  65.  
  66. while true do
  67.     local e, p1, chan, rchan, msg, dist = os.pullEvent()
  68.     if e == "modem_message" then
  69.         write(("\n%d \16 %d | %s\n%s"):format(chan, rchan, dist or "unknown", safe_serialize(msg)))
  70.         local integ = math.floor(chan / divisor) + 1
  71.         set_power(integ, false)
  72.         timers[os.startTimer(0.5)] = integ
  73.     elseif e == "timer" and timers[p1] then
  74.         set_power(timers[p1], true)
  75.     end
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement