Pyeroh

rednetLatch.lua

Oct 18th, 2021 (edited)
492
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local sSide = "back" -- change this if you want to emit redstone signal on another side
  2. local sRednetHost = os.getComputerLabel()
  3. local sProtocol = "rn_redstone"
  4. local sStateFilePath = "latch_state"
  5.  
  6. local fOldPullEvent = os.pullEvent
  7. os.pullEvent = os.pullEventRaw
  8.  
  9. local function detectModem()
  10.     local tPeripherals = {}
  11.     for _,p in pairs(peripheral.getNames()) do
  12.         local sType = peripheral.getType(p)
  13.         if sType == "modem" then
  14.             tPeripherals[#tPeripherals+1] = p
  15.         end
  16.     end
  17.  
  18.     if #tPeripherals ~= 1 then
  19.         return
  20.     else
  21.         return tPeripherals[1]
  22.     end
  23. end
  24.  
  25. local function listener()
  26.     repeat
  27.         rednet.receive(sProtocol)
  28.         print("Change output")
  29.         redstone.setOutput(sSide, not redstone.getOutput(sSide))
  30.  
  31.         local tStateFile = fs.open(sStateFilePath, "w")
  32.         local bState = redstone.getOutput(sSide)
  33.         if bState then
  34.             tStateFile.write("t")
  35.         else
  36.             tStateFile.write("f")
  37.         end
  38.         tStateFile.close()
  39.     until false
  40. end
  41.  
  42. local function initialState(sStateFilePath)
  43.     local tStateFile
  44.     if not fs.exists(sStateFilePath) then
  45.         tStateFile = fs.open(sStateFilePath, "w")
  46.         tStateFile.write("f")
  47.         tStateFile.close()
  48.     end
  49.  
  50.     tStateFile = fs.open(sStateFilePath, "r")
  51.     local sState = tStateFile.readAll()
  52.     tStateFile.close()
  53.  
  54.     return sState == "t"
  55. end
  56.  
  57. local sModemSide = detectModem()
  58. if not sModemSide then
  59.     print("Many modems detected, please place only one modem on the computer.")
  60.     return
  61. end
  62.  
  63. local modem = peripheral.wrap(sModemSide)
  64. if not modem.getNameLocal() then
  65.     print("Configuration error, the modem should be connected.")
  66. end
  67.  
  68. -- set initial state
  69. local bInitialState = initialState(sStateFilePath)
  70. redstone.setOutput(sSide, bInitialState)
  71.  
  72. -- start rednet listener
  73. rednet.open(sModemSide)
  74. rednet.host(sProtocol, sRednetHost)
  75. term.clear()
  76. term.setCursorPos(1, 1)
  77. print("Emitting redstone on the "..sSide)
  78. print("Hosting "..sProtocol.." for host "..sRednetHost)
  79. print("Now listening to redstone messages...")
  80.  
  81. parallel.waitForAny(
  82.     listener,
  83.     function()
  84.         local event = os.pullEventRaw("terminate")
  85.         os.pullEvent = fOldPullEvent
  86.         rednet.unhost(sProtocol)
  87.         rednet.close(sModemSide)
  88.     end
  89. )
RAW Paste Data