MtnMCG

door.lua

Sep 2nd, 2024 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. -- Door computer startup.lua
  2.  
  3. local modem = peripheral.find("modem")
  4. if not modem then error("No modem found. Please attach a wireless modem.") end
  5.  
  6. modem.open(1) -- Use channel 1 for all communications
  7.  
  8. local doorId = nil
  9.  
  10. local function setDoorId()
  11. if fs.exists("door_id.txt") then
  12. local file = fs.open("door_id.txt", "r")
  13. doorId = file.readAll()
  14. file.close()
  15. print("Door ID loaded: " .. doorId)
  16. else
  17. print("Enter the door ID:")
  18. doorId = read()
  19. local file = fs.open("door_id.txt", "w")
  20. file.write(doorId)
  21. file.close()
  22. print("Door ID set and saved: " .. doorId)
  23. end
  24. end
  25.  
  26. local function operateDoor(action)
  27. print("Attempting to " .. action .. " door " .. doorId)
  28. if action == "open" then
  29. -- Set redstone output to bottom (directly powering the door below)
  30. rs.setOutput("bottom", true)
  31. print("Door " .. doorId .. " opened")
  32. sleep(3) -- Keep the door open for 3 seconds
  33. rs.setOutput("bottom", false)
  34. print("Door " .. doorId .. " closed")
  35. else
  36. print("Invalid action: " .. action)
  37. end
  38. end
  39.  
  40. local function monitorAccess()
  41. if not doorId then
  42. error("Door ID is not set. Please restart the computer and set a door ID.")
  43. end
  44.  
  45. print("Monitoring for access requests on channel 1...")
  46. print("This door's ID: " .. doorId)
  47. while true do
  48. local _, _, _, _, message = os.pullEvent("modem_message")
  49.  
  50. -- Only log the type of message and door ID for security reasons
  51. if type(message) == "table" then
  52. print("Received message: {type=" .. (message.type or "nil") .. ", doorId=" .. (message.doorId or "nil") .. "}")
  53.  
  54. if message.type == "door_command" and message.doorId == doorId then
  55. print("Valid door command received for this door")
  56. operateDoor(message.action)
  57. else
  58. print("Ignoring message: not for this door or incorrect format")
  59. end
  60. else
  61. print("Ignoring non-table message")
  62. end
  63. end
  64. end
  65.  
  66. setDoorId()
  67. monitorAccess()
Advertisement
Add Comment
Please, Sign In to add comment